whynotgonow 2020-08-19
我们都知道Promise.all()方法在有一个Promise reject以后,请求结果只返回第一个reject,我们进行了改写,在有请求reject时也可以获取所有结果,并给每个请求添加超时处理。
const promiseall = (all) => { const promiseTimeout = new Promise((resolve, reject) => { setTimeout(() => { reject(‘请求超时‘) },1000) }) return new Promise((resolve, reject) => { const res = new Array(all.length) let count = 0 for(let i=0;i<all.length;i++){ Promise.race([all[i], promiseTimeout]).then((value) => { console.log(value) count ++ res[i] = value if (count === all.length) { return resolve(res) } },(e)=>{ count ++ res[i] = e if (count === all.length) { return resolve(res) } }) } }) } let p = new Promise(function(reslove,reject){ reslove(‘成功1‘) }) let p1 = new Promise(function(reslove,reject){ setTimeout(() => { reslove(‘成功2‘) },2000) }) promiseall([p,p1]).then((res)=> { console.log(res) }).catch((e) => { console.log(e) })