Member-only story
4 JavaScript Promise Methods — All, AllSettled, Any, and Race
Take your asynchronous code to the next level
Promises are great for handling asynchronous operations in JavaScript. Understanding and using them correctly is an essential skill to perform asynchronous operations efficiently.
I would like to share 4 promise methods that I use in my day-to-day tasks. Before moving on to the actual methods, it’s important to understand how we can run promises in sequential/serial and parallel flows.
Consider a function that returns a promise that resolves after 1 second.
Let’s see how we can run promises in sequential/serial flow
On line 2, we are creating a promise and waiting for it to complete before we kick off another promise on line number 3. Since we don’t create the second promise until the first one is resolved, the total execution time is about 2 seconds.
But what if we kick off both the promises at the same time and wait until both resolves
Line 3, and 4 kick off both promises almost at the same time. On line 5, we are just ensuring that the code after line 5 doesn’t get executed until p1
and p2
are resolved. Since both promises run at the same time, the total execution time is about 1 second.
Here is a picture that will make this concept crystal clear