Reputation: 95
I'm not looking for a solution for how to execute promises in sequence, I'm trying to understand the one given by a blog author:
I am reading "We have a problem with promises" by Nolan Lawson, posted 18 May 2015.
Under "Advanced mistake #3: promises vs promise factories" he has this example that is supposed to be the working one:
// Setup, just a meta explanation what a function looks like
function promiseFactory() {
return somethingThatCreatesAPromise();
}
// Actual example; promiseFactories could be an Array
function executeSequentially(promiseFactories) {
var result = Promise.resolve();
promiseFactories.forEach(function (promiseFactory) {
result = result.then(promiseFactory);
});
return result;
}
I don't understand why that works. forEach
executes all functions at once. result
will be a resolved promise so promiseFactory
is run right away?
I don't get how this code is supposed to ensure the code in the promiseFactory
functions runs in sequence.
Upvotes: 2
Views: 96
Reputation: 78545
forEach
executes all functions at once
No, it runs them one after another. forEach
is not asynchronous.
So let's look at an example iteration:
// The first result is already resolved, so as to allow
// the first 'then' to trigger
var result = Promise.resolve();
promiseFactories.forEach(function (promiseFactory) {
// First iteration: result = ResolvedPromise.then(promiseFactory)
// Second iteration result = promiseFactoryResult.then(nextPromiseFactory);
// and so on...
result = result.then(promiseFactory);
});
So it loops through the array-like object, one after another, chaining the result of promises created by the nextPromiseFactory
onto the result
variable.
It's essentially the same as doing:
var result = Promise.resolve().then(promiseFactory).then(promiseFactory).then(promiseFactory);
Upvotes: 3