改写promise并添加超时处理
我们都知道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) })
相关推荐
nmgxzm00 2020-11-10
xixixi 2020-11-11
88254251 2020-11-01
MarukoMa 2020-09-02
88234852 2020-09-15
陈旭阳 2020-08-31
前端开发Kingcean 2020-07-30
whynotgonow 2020-07-29
bowean 2020-07-08
前端开发Kingcean 2020-07-08
88520191 2020-07-05
前端开发Kingcean 2020-06-27
88481456 2020-06-18
whynotgonow 2020-06-16
88520191 2020-06-13
88520191 2020-06-13
89500297 2020-06-13
前端开发Kingcean 2020-06-11