adding promises to an array of promises in a for loop [duplicate]

泄露秘密 提交于 2019-12-07 12:12:52

问题


let's assume the following example:

var bb = require('bluebird');

var promiseStack = [];
var deferred = bb.defer();

promiseStack.push(deferred.promise);

bb.delay(2500).then(function() {
    deferred.resolve();
});

bb.all(promiseStack).then(function() {
    console.log('done');
});

Why isn't it possible to do the following:

var bb = require('bluebird');

var promiseStack = [];


for(var i = 1; i < 10; i++) {
    var deferred = bb.defer();
    promiseStack.push(deferred.promise);

    bb.delay(2500).then(function() {
        deferred.resolve();
    });
}

bb.all(promiseStack).then(function() {
    console.log('done');
});

It takes aprox. 2500ms but console.log('done') isn't called. What's the problem with, am I doing wrong?

The best, redshark1802


回答1:


What's the problem with, am I doing wrong?

Your deferred variable is not local to the loop body, but on a global scope. You're overwriting it each time with a new Deferred, and resolving only the last of them (but multiple times).

To fix it, you could try a closure, but you shouldn't use Deferred anyway. Just use the promise you already have!

var bb = require('bluebird');

var promiseStack = [];

for(var i = 1; i < 10; i++) // 1 to 9 ???
    promiseStack.push( bb.delay(2500) );

bb.all(promiseStack).then(function() {
    console.log('done');
});


来源:https://stackoverflow.com/questions/21885073/adding-promises-to-an-array-of-promises-in-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!