There are many answers for this question, but most of them synchronize the resolution of the promises (i.e. the end of execution, not the beginning of execution).
This solution assumes we already have an array of functions:
var funcs = [foo, bar, baz, qux];
How is such array created without executing the functions? I have tried this:
var promises = [];
for (i = 0 ; i < 3, ++i){
promises.push( someFunction(i) )
}
function someFunction(i) {
return new Promise((resolve, reject) => {
console.log(i);
resolve(i);
});
}
By the end of for loop the promises array is populated, but someFunction
is already executed 4 times. Using Promise.all
or Q
sequences just sequences resolves.
How can I achieve the true synchronization of beginning of these functions? In particular:
foo().then(bar).then(baz).then(qux);
----------------------------------------------------------------
Update (Simple Solution using Async Functions):
The simple way to do this is to use async
functions and await
. See this answer for an example of calling the promise in a loop, where each promise will be called when the previous one is resolved.