Open huixisheng opened 5 years ago
javascript - Node.js异步库比较-Q vs Async JavaScript 异步开发攻略 Why Using reduce() to Sequentially Resolve Promises Works | CSS-Tricks JavaScript Promise启示录 · Issue #6 · chemdemo/chemdemo.github.io 潜入理解ES6-Promise用法小结 - 掘金 Promise 异步流程控制 - 知乎 JavaScript Promise:简介 | Web | Google Developers Using promises | MDN Sequential execution of Promises using reduce() ES6 Promise Anti-Patterns and Best Practices 4.8. 使用Promise进行顺序(sequence)处理 · JavaScript Promise迷你书(中文版) · 看云 Use Reduce() and Promises to Execute Multiple Async Calls Sequentially (14) 精读《用 Reduce 实现 Promise 串行执行》 - 前端精读专栏 - SegmentFault 思否
function func1() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('func1');
}, 100)
});
}
function func2() {
return 'func2';
}
function func3() {
return 'func3';
}
// Promise.resolve().then(func1).then(func2).then(func3);
[func1, func2, func3].reduce((p, f) => {
console.log(f);
console.log(p);
return p.then(f)
}, Promise.resolve())
.then(result3 => {
console.log('reduce', result3);
});
Promise.all([func1(), func2(), func3()])
.then(([result1, result2, result3]) => {
console.log('Promise.all', result1, result2, result3);
});
const applyAsync = (acc, val) => acc.then(val);
const composeAsync = (...funcs) => x => funcs.reduce(applyAsync, Promise.resolve(x));
const transformData = composeAsync(func1, func2, func3);
transformData().then((result3) => {
console.log('composeAsync', result3);
});
// [Function: func1]
// Promise { undefined }
// [Function: func2]
// Promise { <pending> }
// [Function: func3]
// Promise { <pending> }
// Promise.all func1 func2 func3
// reduce func3
// composeAsync func3
// let result;
// for (const f of [func1, func2, func3]) {
// result = await f(result);
// }
// console.log(result)
参考
https://github.com/Tencent/wepy/blob/fdfdbd390a81aab3b38758096d89f74405c3c10e/packages/cli/core/hook.js#L69-L103