As georg said, you’re just not putting the promises in arr
, because you never return anything from the anonymous function you’ve wrapped around new Promise
. That function is also completely unnecessary, so:
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);
}
If the function is there so you can capture the then-current value of i
, just ensure you return the 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);
}