Guarantees are nice for dealing with asynchronous operations in JavaScript. Understanding and utilizing them accurately is a necessary ability to carry out asynchronous operations effectively.
I want to share 4 promise strategies that I take advantage of in my day-to-day duties. Earlier than shifting on to the precise strategies, it’s vital to grasp how we will run guarantees in sequential/serial and parallel flows.
Think about a perform that returns a promise that resolves after 1 second.
Let’s see how we will run guarantees in sequential/serial stream
On line 2, we’re crconsuming a promise and ready for it to finish earlier than we kick off one other promise on line quantity 3. Since we don’t create the second promise till the primary one is resolved, the full execution time is about 2 seconds.
However what if we kick off each the guarantees on the similar time and wait till each resolves
Line 3, and 4 kick off each guarantees virtually on the similar time. On line 5, we’re simply guaranteeing that the code after line 5 doesn’t get executed till p1
and p2
are resolved. Since each guarantees run on the similar time, the full execution time is about 1 second.
Here’s a image that may make this idea crystal clear
There are 5 asynchronous duties.
On the left:
- Duties are kicked off parallelly.
- Complete execution time is the time of the longest activity.
On the fitting:
- Duties are kicked off one after one other.
- Complete execution time is the mixed time of all duties.
Observe that guarantees begin their activity when they’re being created. Promise.all
simply waits till all of the given guarantees are resolved.