So in the last post, we learned about how promises work in javascript.
Today, we gonna learn about how async-await works together for the seamless working of promises and makes the developer experience better.
The concept of async-await comes into use when we have more than 2 promises, the code becomes messy and sometimes unbearable.
If you remember the previous example of making a promise, that's great. If not here it is:
const isNumEven = (num) => new Promise((resolve, reject)=> {
if(num % 2 === 0) {
resolve(true)
} else {
reject(false)
}
})
Now this promise can be used as:
async function isEven(num) {
try {
const result = await isNumEven(num);
return result;
} catch(err) {
console.log('Something went wrong!')
}
}
isEven(4); // true
As you can see, it makes our code less sloppy and easier to manage. Now if the isNumEven function returns another promise, then we can use await again and get the result.
Now some of you must be wondering why try catch is used in this example?
The answer to this is error handling. If any of the statements fail in the try block, then the code directly goes into the catch block. So, if our promise fails, the error will be handled by the catch block.
Some important points related to async await:
Avoid using it inside
forloops, and if there is a need to perform an operation on all entities usePromise.allrather thanasync await.If you have used the
asynckeyword before a function, it'll return a promise every time.Async await is just syntactic sugar for promises, the code runs the same way as it runs for promises. The code looks synchronous and the program waits until the promise is resolved.
If a function is
async, then only you can useawaitinside it.
Connect with me on Twitter, Instagram & LinkedIn
Happy Coding!
Top comments (0)