Promise和Promise.all(数组)在数组实现之前执行
Promise and Promise.all(array) executed before array fulfilled
Promise.all(arr).then
回调在数组完成之前执行,因此它不会捕获其元素。我怎样才能正确地做到这一点?
var arr = [];
for (var i = 0; i < 2; i++) {
arr.push((function() {
new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("Resolved!");
resolve();
}, 3000);
});
})());
}
Promise.all(arr).then(function() {
console.log("Done");
});
我的预期结果是:
Resolved!
Resolved!
Done
但真正的结果是:
Done
Resolved!
Resolved!
上面的代码只是一个例子。我更改了如下结构,代码不再有问题,但由于我的应用程序结构,我应该使用for
循环和push
。
var p1 = new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("Resolved #1");
resolve();
}, 1000);
});
var p2 = new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("Resolved #2");
resolve();
}, 2000);
});
var arr = [p1, p2];
Promise.all(arr).then(function() {
console.log("Done");
});
正如georg所说,您只是没有将promise放在arr
中,因为您从未从围绕new Promise
封装的匿名函数返回任何内容。这个功能也是完全没有必要的,所以:
var arr = [];
for (var i = 0; i < 2; i++) {
arr.push(new Promise(function(resolve, reject) {
setTimeout(function() {
log('resolved !');
resolve();
}, 500);
}));
}
Promise.all(arr).then(function() {
log("Done");
});
function log(msg) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}
如果函数存在,那么您可以捕获i
的当前值,只需确保您返回promise:
var arr = [];
for (var i = 0; i < 2; i++) {
arr.push(function(index) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
log('resolved with ' + index + ' !');
resolve(index);
}, 500);
});
}(i));
}
Promise.all(arr).then(function() {
log("Done");
});
function log(msg) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}
相关文章:
- Promise没有;t返回对象的数组
- $q.all当输入数组中的一项不是promise时,Typescript检查器失败
- 当数组中的某个函数没有返回promise时,我可以使用$q.all吗
- promise数组中的WinJS返回
- 使用Node中的Q promise库对值数组顺序调用/执行相同的函数;并返回带有结果的新数组/集合
- 序列promise链与数组数据,如何解析promise链
- Promise和Promise.all(数组)在数组实现之前执行
- 如果数组中的值为false,则破坏Promise
- 在多维数组中获取promise的结果
- 在使用promise数组时使用jQuery
- 包含 promise 的对象数组在 for 循环中混乱
- ngResource.myfunc().$promise.then 返回空数组
- ES6 Promise.all() promise 数组的奇怪分辨率
- 如何使用 Parse.promise javascript 定义一个承诺数组并获取结果数组 [parse.com]
- 节点.js不能使用 promise、Mongoose 和 GET 请求推送到全局数组
- 为什么在 Promise.all() 之后没有调用 onJect,其中数组中包含的 Promise.reject() 传
- Promise.all 在完成之前返回一个未定义和解析的数组
- 将一个q promise数组拆分为多个数据包,并依次运行这些数据包
- $when.apply在promise数组中的某个promise被延迟时不工作
- 在PouchDB/Barket.js中推送promise数组之前修改对象的值