Javascript promise basics
Many developers have some tough time understanding promises in javascript.
We will try to understand promise in javascript through some basic examples.
- Create and use promise:
someTask is a function which returns a promise. When async task is successfully completed, we can call resolve and if there is some error we will use reject.
When we call a function which returns a promise,
- ‘.then’ is executed if promise completes successfully(resolved)
- ‘.catch’ if promise fails(rejected)
Both tasks here are independent, second task doesn't wait for the first to be resolved.
someTask() can do any async task like HTTP call, DB call, filesystem call, etc
2. Async Await
Async await is a sugar syntax to call functions which return a promise. It gets easy to call 2 promise based function’s one after other(which is not the case in the previous example).
But what if when we don't want to wait for the first promise to resolve to call the second promise?
3. Promise.all
We can await all promises together using Promise.all(array of promises).
Our program completes after 400 ms and not 700 ms.
4. Promise.all hybrid solution
Here we have 9 tasks to perform and we don't want to start all 9 together for some performance reason. So we call promises in a batch of 2 at time. This way we can balance performance and speed.
5. Promise.all with individual catch
If one promise fails in an array of promise.all, promise.all will throw an error.
To avoid this, before giving promise to an array of promise.all, we can add a catch block to it.
Through examples, we have created a custom promise, used .then and .catch, used async-await, used promise.all and hybrid promise.all(batch of n promises).
Other methods to consider for promise are race, allSettled, any.
Git repo: https://github.com/riddheshganatra/Javascript-promise-basics
We at Code B are a team of Fullstack software developers, passionate and dedicated to growing businesses for clients.
We have experience in Web Applications(Frontend and Backend), Mobile Applications(Native and Hybrid), DevOps (AWS, GCP, Azure, Digital Ocean, and Heroku), Blockchain(Solana), and UI/UX Design(Figma).
Contact us if you need any help with Software.