pipeAsyncFunctions

时间:2022-07-24
本文章向大家介绍pipeAsyncFunctions,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

从左向右的顺序组合异步函数并依次执行他们。


使用两层高阶函数

第一层高阶函数用于在闭包中保存需要执行的异步函数数组(异步函数作为参数传入,并通过数组展开操作符...保存在数组fns中)。

第二层高阶函数用于在闭包中保存传给异步函数数组的初始参数。

异步函数数组使用 Array.prototype.reduce()遍历执行,作为promise通过Promise.then()连接。

所有异步函数只能接受一个参数

const pipeAsyncFunctions = (...fns) => {
  return arg => {
    return fns.reduce(
      (prev, curFn) => prev.then(curFn),
      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
);

// 一秒后打印 15
(async() => {
  console.log(await sum(5)); 
})();

扩展阅读

从左向右的顺序组合同步函数并依次执行他们。

使用一层高阶函数

高阶函数用于在闭包中保存需要执行的同步函数数组(同步函数作为参数传入,并通过数组展开操作符...保存在数组fns中)。

通过 Array.prototype.reduce()不断返回嵌套执行的函数

最终返回的函数执行时,第一个传递给pipeFunctions同步函数可以接收多个参数。之后的每个同步函数只能接受上一个函数的返回值作为参数

const pipeFunctions = (...fns) => {
  return fns.reduce((prevFn, curFn) => {
      return (...args) => curFn(
        prevFn(...args)
      );
    }
  );
}
const add5 = x => x + 5;
const multiply = (x, y) => x * y;

const multiplyAndAdd5 = pipeFunctions(
  multiply, add5
);

// 15
multiplyAndAdd5(5, 2);