In an attempt to understand promises more clearly, i have been reading up a few very interesting articles on the same. I came across the following code which works perfectly for executing promises sequentially. But i am not able to understand how it works.
function doFirstThing(){ return new Promise(function(resolve,reject){ setTimeout(()=>{ resolve(1); },1000) }) } function doSecondThing(res){ return new Promise(function(resolve,reject){ setTimeout(()=>{ resolve(res + 1); },1000) }) } function doThirdThing(res){ return new Promise(function(resolve,reject){ setTimeout(()=>{ resolve(res + 2); },1000) }) } promiseFactories = [doFirstThing, doSecondThing, doThirdThing]; function executeSequentially(promiseFactories) { var result = Promise.resolve(); // this is the most problematic line promiseFactories.forEach(function (promiseFactory) { result = result.then(promiseFactory);// what is happening here ? }); return result; } executeSequentially(promiseFactories) I do understand that promises are executed as soon as they are created. For some reason i am not able to understand the flow of execution. Especially this following line:
var result = Promise.resolve()//and empty promise is created. Please if somebody can help me understand how calling the promiseFactory method inside the 'then' method of the empty promise makes it execute sequentially, like so. Or is it because of the forEach loop ?
result = result.then(promiseFactory); I tried replacing the 'forEach' with a 'map' function and still yielded the same result. i.e, the methods where executed sequentially. Also, how is the value passed from one chained function to other ?
Any help or article/blog is highly appreciated.