关于promise:await-与-Promiseall-结合使用

11次阅读

共计 490 个字符,预计需要花费 2 分钟才能阅读完成。

当遇到多个能够同时执行的异步工作时,就须要应用 Promise.all。

Promise.all 办法用于将多个 Promise 实例,包装成一个新的 Promise 实例。
const p = Promise.all([p1, p2, p3])
Promise.all 办法承受一个数组作为参数,p1、p2、p3 都是 Promise 实例,如果不是,就会先调用 Promise.resolve 办法,将参数转为 Promise 实例,再进一步解决。(Promise.all 办法的参数能够不是数组,但必须具备 Iterator 接口,且返回的每个成员都是 Promise 实例。)

而 async/await 自身就是 promise 的语法糖,因而能够与 Promise.all 联合应用:

const p1 = async () => {}
const p2 = async () => {}
const p3 = async () => {}

const [result1, result2, result3] = await Promise.all([p1, p2, p3])

console.log(result1)
console.log(result2)
console.log(result3)
正文完
 0