为异步函数执行从左到右的函数组合
使用Array.prototype.reduce()和展开运算符 ( ...) 来执行使用Promise.prototype.then().
这些函数可以返回正常值Promises 或 async 的组合,通过 . 返回await。
所有函数都必须接受一个参数。
JavaScript
constpipeAsyncFunctions=(...fns)=>
arg=>fns.reduce((p,f)=>p.then(f),Promise.resolve(arg));
示例代码:
const sum = pipeAsyncFunctions(
x => x + 1,
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
x => x + 3,
async x => (await x) + 4
);
(async() => {
console.log(await sum(5)); // 15 (after one second)
})();
更多内容请访问我的网站:https://www.icoderoad.com