Open vaakian opened 2 years ago
Promise.all是并行的,此处3种方法实现串行Promise
function f1() { return new Promise((resolve) => { setTimeout(() => { resolve('A') }, 300) }) } function f2() { return new Promise((resolve) => { setTimeout(() => { resolve('B') }, 100) }) } function f3() { return new Promise((resolve) => { setTimeout(() => { resolve('C') }, 110) }) } // 1. 递归法,最简单 function serialPromise1(promises = [], i = 0) { promises[i]().then(data => { console.log(data) i + 1 < promises.length && serialPromise2(promises, i + 1) }) } // 2. 语法糖迭代法 async function serialPromise2(promises = []) { for (let i = 0; i < promises.length; ++i) { let res = await promises[i]() console.log(res) } } // 3. 抛去语法糖外衣的迭代法 const serialPromise3 = function (promises = []) { // promises.reduce((prev, next, i) => { // return prev.then(next).then(data => console.log({ data, i })) // }, Promise.resolve()); let p = Promise.resolve() for (let i = 0; i < promises.length; ++i) { p = p.then(promises[i]) p.then(data => console.log(data)) } } serialPromise3([f1, f2, f3])
Promise.all是并行的,此处3种方法实现串行Promise