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

Viewed 664

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?

2 Answers
Related