Skip to content
This repository has been archived by the owner on Feb 9, 2021. It is now read-only.

函数式编程 —— Promise 序列实例化 #26

Open
lbwa opened this issue Sep 19, 2018 · 0 comments
Open

函数式编程 —— Promise 序列实例化 #26

lbwa opened this issue Sep 19, 2018 · 0 comments
Labels
Code skill Skill from coding Pure JS Pure JavaScript .etc

Comments

@lbwa
Copy link
Owner

lbwa commented Sep 19, 2018

实现 Promise 的顺序实例化,即仅当前一个 Promise 实例化状态 resolved 之后才开始调用下一个 Promise 实例化。此举不同于 Promise.all[].map() 中的并发实例化 Promise

/**
 * 
 * @param {promise[]} funcs 待实例化数组
 */
const promiseSerial = funcs => 
  funcs.reduce((promise, func) =>
    // 待上一次 promise 的状态 resolved 之后,调用下一个 promise,即 func
    // 并将运行 func 得到的结果与之前的 promise 返回的结果合并
    promise
      .then(result => func().then(Array.prototype.concat.bind(result)))
      .catch(console.error),
    // 初始值为一个空数组容器
    Promise.resolve([])
  )

Reference

@lbwa lbwa added Pure JS Pure JavaScript .etc Code skill Skill from coding labels Sep 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Code skill Skill from coding Pure JS Pure JavaScript .etc
Projects
None yet
Development

No branches or pull requests

1 participant