Given an array of Promises, we have to run that in a series. To do this task, we can use then(), to run the next promise, after completion of a promise.
Approach: The then() method returns a Promise, which helps us to chain promises/methods. The Promise.resolve() method executes the first callback, and when this promise is fulfilled, then it passes to the next function callback1, and it goes on until all the promises are fulfilled. In this way, we can run all the Promises in series.
Promise.resolve( callback0 ) .then( callback1 ) .then( callback2 ) .then( callback3 )...
Example 1: In this example, we will be executing 3 promises by chaining each of them with the then() method.
https://www.facebook.com will be fetched now https://www.twitter.com will be fetched now
The above approach is not feasible if there are a lot more promises in the array. Chaining of the function would get very tiring and will make the code lengthy. We can use the forEach() array function to execute the promises by storing the results in a variable and updating that variable at every promise. This will automatically go through all the promises and one can prevent repeatedly writing then() statements.
Example 2: In this example, we will be executing multiple promises by using the forEach() method.