Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

精读《用 Reduce 实现 Promise 串行执行》 #109

Closed
ascoders opened this issue Oct 24, 2018 · 6 comments
Closed

精读《用 Reduce 实现 Promise 串行执行》 #109

ascoders opened this issue Oct 24, 2018 · 6 comments

Comments

@ascoders
Copy link
Owner

本周精读的文章是:why-using-reduce-to-sequentially-resolve-promises-works

Promise.all 可以并行解决处理所有异步 Promise,但 Promise 串行执行却没有现成的 API,本文推荐了 reduce 方式解决 Promise 串行执行的思路值得学习。

@atian25
Copy link

atian25 commented Oct 24, 2018

https://github.com/sindresorhus/promise-fun

@eos3tion
Copy link
Contributor

额,串行执行不是直接下面这种方法就行的么?

async function chuanxing(promises){
    for(let i=0;i<promises.length;i++){
        await promises[i];
    }
}

@atian25
Copy link

atian25 commented Oct 24, 2018

指的是没有 async 的场景

@kangenpingmai
Copy link

如果任务队列中的函数都依赖上一个返回值的函数改怎么写呢

@lesonky
Copy link

lesonky commented Oct 29, 2019

如果任务队列中的函数都依赖上一个返回值的函数改怎么写呢

let userIDs = [1,2,3];

userIDs.reduce( async (previousPromise, nextID) => {
  // 这里可以获取前一个 promise 的返回值
  const previousResolve = await previousPromise;
  // 拿到返回值后可以到下面去用 
  // 第一个返回值是一个空的,因为reduce 的起始值是 Promise.resolve(),
  // 如果要给第一个函数也加一个参数,可以用 Promise.resolve('XXX'),
  // 这样第一个函数调用的时候也会有一个参数 XXX
  return methodThatReturnsAPromise(nextID,previousResolve);
}, Promise.resolve());

@tkgkn
Copy link

tkgkn commented Dec 8, 2021

复杂一点如,多个任务,得按照顺序来交互,每个任务又是异步,这个场景也能用到串行Promise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants