huixisheng / huixisheng.github.com

前端开发者说,记录前端的故事
http://huixisheng.github.io/
12 stars 3 forks source link

reduce promise chain #37

Open huixisheng opened 5 years ago

huixisheng commented 5 years ago

https://github.com/Tencent/wepy/blob/fdfdbd390a81aab3b38758096d89f74405c3c10e/packages/cli/core/hook.js#L69-L103

hookAsyncSeq (key, ...args) {
    let rst = args;
    let hooks = this._hooks[key] || [];

    let count = 0;
    let allRst = [];
    let lastRst = rst;
    let argLength = args.length;

    if (hooks.length === 0) {
      return Promise.resolve(argLength === 1 ? args[0] : args);
    }

    return new Promise((resolve, reject) => {
      const iterateFunc = (pfn, cfn) => {
        return pfn.then(v => {
          if (!Array.isArray(v)) {
            v = [v];
          }
          if (count++ !== 0) {
            allRst = allRst.concat(v);
          }
          lastRst = v;
          return cfn.apply(this, lastRst);
        }).catch(e => {
          reject(e);
        })
      }

      hooks = hooks.concat(() => Promise.resolve());
      hooks.reduce(iterateFunc, Promise.resolve(args)).then(() => {
        resolve(argLength === 1 ? lastRst[0] : lastRst);
      });
    });
  }
huixisheng commented 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 思否

huixisheng commented 5 years ago

Functional JavaScript: Resolving Promises Sequentially Promise.reduce | bluebird

huixisheng commented 5 years ago

小技巧:使用Array.reduce创建Promise回调链 - 掘金 Best Practices for Using Promises in JS | 60devs

huixisheng commented 5 years ago
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)

参考