promise.all的作用
将多个Promise实例包装成一个新的Promise实例。
成功时返回一个结果数组
失败的时候返回最先被reject失败状态的值
明确需求
返回的是一个promise,传入的是一个可迭代对象
遍历数组中的promise放入结果数组中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| function PromiseAll(args) { return new Promise((resolve, reject) => { const PromiseResults = []; let iteindex = 0; let fullcount = 0; for (const item of args) { let resIndex = iteindex; iteindex++; Promise.resolve(item).then(res => { PromiseResults[resIndex] = res; fullcount++; if (fullcount === iteindex) { resolve(PromiseResults); } }).catch(err => { reject(err); }) } if (iteindex === 0) { resolve(PromiseResults); } }) } let p1 = new Promise((res, rej) => { setTimeout(() => { res(111); }, 1000) }); let p2 = new Promise((res, rej) => { setTimeout(() => { res(222); }, 2000) }); PromiseAll([p1, p2]).then(res => console.log(res));
|