javascript 将承诺添加到 for 循环中的承诺数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21885073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:54:20  来源:igfitidea点击:

adding promises to an array of promises in a for loop

javascriptnode.jspromisebluebird

提问by redshark1802

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?

它需要大约。2500 毫秒,但console.log('done')没有被调用。有什么问题,我做错了吗?

The best, redshark1802

最好的,redshark1802

回答by Bergi

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

有什么问题,我做错了吗?

Your deferredvariable 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).

您的deferred变量不是循环体的局部变量,而是在全局范围内。你每次都用一个新的 Deferred 覆盖它,并且只解决最后一个(但多次)。

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

要修复它,您可以尝试使用closure,但无论如何都不应该使用Deferred。只需使用您已有的承诺!

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');
});