🎶 Sym - 一款用 Java 实现的现代化社区(论坛/BBS/社交网络/博客)平台

📕 思源笔记 - 一款桌面端笔记应用,支持 Windows、Mac 和 Linux

🎸 Solo - B3log 分布式社区的博客端节点,欢迎加入下一代社区网络

♏ Vditor - 一款浏览器端的 Markdown 编辑器

功能 - 异步函数管道

2019-03-29

描述

为输入的异步函数进行从左到右的依次执行。

提示

  • 对接受的函数参数使用扩展运算符后便可用 Array.prototype.reduce() 来执行从左到右的函数组合。
  • 为接受的异步函数使用 Promise.then()
  • 接受的函数参数可以返回以下组合:简单值, Promise ,或者定义为 async 函数且通过 await 返回的异步值。所有函数必须是一元的。

代码

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 (after one second)
})();

返回总目录

每天 30 秒系列之 JavaScript 代码


欢迎注册黑客派社区,开启你的博客之旅。让学习和分享成为一种习惯!

推荐阅读
留下你的脚步