Search code examples
javascriptforeachpromiseparse-serverfor-of-loop

Creating Promises in for...of loop instead forEach?


I want to execute an array of Promises in parallel and then wait until all Promises are executed.

This works:

var promises = [];

objects.forEach(function(object) {

    let promise = new Parse.Promise.as()
    .then(
        function() {
            return destroy(object);
        }
    );

    promises.push(promise);
});

return Parse.Promise.when(promises);

But if I use for (object of objects) {...} instead of objects.forEach(function(object) {...}); it doesn't work. For every Promise in the array the destroy(object); is executed on the first object in the array:

var promises = [];

for (object of objects) {

    let promise = new Parse.Promise.as()
    .then(
        function() {
            return destroy(object);
        }
    );

    promises.push(promise);
});

return Parse.Promise.when(promises);

Why is that?


Solution

  • Yes, you forgot to declare the object variable as local to the loop body (see also the canonical explanation):

    var promises = [];
    for (let object of objects) {
    //   ^^^
        promises.push(new Parse.Promise.as().then(function() {
            return destroy(object);
        }));
    }
    return Parse.Promise.when(promises);
    

    Of course you should not do this either, you should just use map:

    var promises = objects.map(function(object) {
        return new Parse.Promise.as().then(function() {
            return destroy(object);
        });
    });
    return Parse.Promise.when(promises);