Javascript :: pipeAsyncFunctions

对异步功能执行从左到右的功能组合。

 与散布运算符()一起使用 可以执行从左到右的功能合成 。这些函数可以返回以下各项的组合:简单值, 也可以将它们定义为  通过返回的值 。所有函数必须是一元的。Array.prototype.reduce()...Promise.then()Promiseasyncawait

const pipeAsyncFunctions = (...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(一秒钟后)
})();