Node.js 原生 Promise.all 是并行处理还是顺序处理? [英] Is Node.js native Promise.all processing in parallel or sequentially?

查看:22
本文介绍了Node.js 原生 Promise.all 是并行处理还是顺序处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想澄清这一点,作为文档 不太清楚;

I would like to clarify this point, as the documentation is not too clear about it;

Q1: Promise.all(iterable) 是按顺序还是并行处理所有 promise?或者,更具体地说,它是否相当于运行像

Q1: Is Promise.all(iterable) processing all promises sequentially or in parallel? Or, more specifically, is it the equivalent of running chained promises like

p1.then(p2).then(p3).then(p4).then(p5)....

或者是其他某种算法,其中所有 p1p2p3p4p5 等同时(并行)被调用,并且在所有解决(或一个拒绝)后立即返回结果?

or is it some other kind of algorithm where all p1, p2, p3, p4, p5, etc. are being called at the same time (in parallel) and results are returned as soon as all resolve (or one rejects)?

问题 2:如果 Promise.all 并行运行,有没有方便的方法来顺序运行可迭代对象?

Q2: If Promise.all runs in parallel, is there a convenient way to run an iterable sequencially?

注意:我不想使用 Q 或 Bluebird,而是所有原生 ES6 规范.

Note: I don't want to use Q, or Bluebird, but all native ES6 specs.

推荐答案

Promise.all(iterable) 是否正在执行所有的 Promise?

Is Promise.all(iterable) executing all promises?

不,承诺不能被执行".他们在创建时开始他们的任务——他们只代表结果——并且甚至在将它们传递给Promise.all之前并行执行所有事情代码>.

No, promises cannot "be executed". They start their task when they are being created - they represent the results only - and you are executing everything in parallel even before passing them to Promise.all.

Promise.allawait 多个承诺.它不关心它们以什么顺序解析,或者计算是否并行运行.

Promise.all does only await multiple promises. It doesn't care in what order they resolve, or whether the computations are running in parallel.

有没有一种方便的方法可以按顺序运行可迭代对象?

is there a convenient way to run an iterable sequencially?

如果你已经有你的承诺,除了 Promise.all([p1, p2, p3, ...])(它没有序列的概念),你不能做太多事情.但是,如果您确实有可迭代的异步函数,则确实可以按顺序运行它们.基本上你需要从

If you already have your promises, you can't do much but Promise.all([p1, p2, p3, …]) (which does not have a notion of sequence). But if you do have an iterable of asynchronous functions, you can indeed run them sequentially. Basically you need to get from

[fn1, fn2, fn3, …]

fn1().then(fn2).then(fn3).then(…)

解决方案是使用 Array::reduce:

and the solution to do that is using Array::reduce:

iterable.reduce((p, fn) => p.then(fn), Promise.resolve())

这篇关于Node.js 原生 Promise.all 是并行处理还是顺序处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆