Parallel & Sequential handling Javascript Promise
We fulfil and reject several promises every day. Some in personal life and some in Javascript. Sadly there are no perfect formulae to help out in personal life, but in Javascript, we can do something. In this article, I explore 4 ways we can iterate and resolve an array of promises in parallel and sequentially.
Before we get to the main stuff, let’s go through some basic ways of resolving promise/s.
const fetchData = () => { ...return promise }fetchData.then((result) => ... do something with result ...)// With async await
const result = await fetchData();
... do something with result ...
And when we get a array of promises
const result = await Promise.all( ... promises )
But there is more we can do with array of promises by playing around with array functions. First let’s create a promise array we will resolve in our examples below.
Parallel resolving
Asynchronous parallel resolving of promises can be done with Promise.all
and Promise.allSettled
. We can create an array of all the async functions and use these methods to await until all the promise are resolved.
Now the difference between Promise.all and Promise.allSettled is that the earlier will reject the promise as soon as any of the given promise rejects. Whereas the later will always resolve with array of result [{status: 'fulfilled', value: {}}, ...]
for each of the promise given.
The above methods are good for all the asynchronous requirements. But what when we want to execute promises one-after-another in a synchronous way. Let’s see a few ways of doing it.
Promise Chain
Here we will use Array.reduce to create a Promise chain. On resolving all the promises resolve sequentially.
Notice the sequence of fruits in output is the same as created above in promiseGenerators.js
For-of loop
Loop through each promise, await it and collect results from each one. Though if you use await in a loop you will see warning from eslint. This approach is not very promisy 😄. But it’s ok to suppress the warning and continue with this approach for a sequential execution.
Nested then() callback
Lastly we can create a recursive function to loop through all the promises and create a nested then() callback to sequentially execute all the promises. Though this is my least preferred way as this looks complicated to understand, I included it here as ……. hey!! we are exploring 😄
Feel free to fork and play around with code here
So thats all I have with me for now. Let me know if you have any interesting way of resolving promise or array of promises.
Happy Coding !!