[英]Promise.all on same array
I'm looking at promises-based code that does something like this: 我正在看基于promise的代码,它执行以下操作:
var promises = [];
function eventHandler(e)
{
promises.push(getSomeData(e.opts));
Promise.all(promises)
.then(...)
.then(function()
{
promises = [];
});
}
Shouldn't the Promise.all
based promise execute as many times as the eventHandler
is called? 基于
Promise.all
是否应该与Promise.all
eventHandler
一样执行多次?
EDIT: what's happening here is the event handler gets called a few times and the previous promises are not finished yet. 编辑:这里发生的是事件处理程序被调用了几次,之前的承诺还没有完成。 I need a way to be able to extend the list of promises and have only one final
then
run. 我需要一种方法,能够延长承诺的名单上,只有一个最后
then
运行。
Update, OP has clarified they'd like to wait for all promises added before the original ones resolved as well - .all
does not do this. 更新,OP明确表示,他们希望在原始承诺也解决之前等待所有添加的承诺
.all
不这样做。 Instead you can use thenable chaining. 相反,您可以使用随后的链接。
var p = Promise.resolve([]); // create empty array promise, `when` in dojo
function eventHandler(e){
p = p.then(function(value){ // chain off the last value
return getSomeData(e.opts).then(function(single){
return value.push(single); // add to the array
});
});
}
This will add an item to the array each time the eventHandler is called - every time you .then
it you will get the current values and not the last ones - but you can .then
it as many times as you'd like. 每次调用eventHandler时,这都会在数组中添加一个项目-每次您将
.then
它将获得当前值,而不是最后一个值-但您可以.then
多次。 You can for example chain on when no events happened since the chaining time by: 例如,您可以通过以下方式链接:自链接时间以来何时未发生任何事件:
var p2 == p;
p.then(function(results){
if(p !== p2) return p; // wait in case more events happened, but no more
return results;
});
Or wait for as long as you'd like: 或等待,只要您愿意:
function noMoreAddedInterim(){
var p2 = p;
return p.then(function(results){
if(p2 !== p) return noMoreAddedInterim(); // changed
else return results; // no more added
});
}
You have a race condition, you're calling Promise.all
and only cleaning the array later so many promises are in the results twice or more. 您有一个竞争条件,您要致电
Promise.all
然后仅在以后清洗阵列,因此结果中会有很多许诺两次或多次。
Instead - put promises
in a temporary variable, .all
that and clear promises
before the .then
. 相反,将
promises
放在一个临时变量.all
,然后在.then
之前清除promises
。 Since you're adding promises one at a time you probably don't even need the .all
here. 由于您一次添加了一个
.all
您甚至都不需要.all
。
Also, you should attach a .catch handler to not miss any errors. 另外,您应该附加.catch处理程序,以免遗漏任何错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.