Node.js是原生的Promise.all并行或顺序处理吗? [英] Is Node.js native Promise.all processing in parallel or sequentially?
问题描述
我想澄清这一点,如文档对此不太清楚;
I would like to clarify this point, as the documentation is not too clear about it;
Q1: Promise.all(可迭代)
顺序或并行处理所有承诺?或者,更具体地说,它是否相当于运行链式承诺,如
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)....
还是其他一种算法所有 p1
, p2
, p3
,<$ c同时调用$ c> p4 , p5
等(并行),并在所有解析后立即返回结果(或者一个拒绝)?
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)?
Q2:如果 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(可迭代)
执行所有承诺?
不,承诺不能执行。他们在创建时开始他们的任务 - 他们只代表结果 - 并且你甚至在将它们传递给 Promise之前并行执行所有内容。全部
。
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.all
只做 await 多重承诺。它不关心它们解决的顺序,或者计算是否并行运行。
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屋!