I'm sure you all have heard at least a million times by now that Async&Await is just a better way to write Promises. Well, how better is the question?
Well first have a look at this primitive way of writing Promises that we talked about in our previous article.
//declaring our Promise returning function
function promiseExample(number) {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
if(number%2==0)
resolve('even')
else
reject('odd') },5000)//5 seconds delay
})
}
//now calling the function
promiseExample(5)
.then(result=>console.log(`${result} number`))
.then(()=>console.log("Hurray we did it")
.then(()=>console.log('aaghh I can finally go to sleep now')
.then(()=>console.log('zzzzzzzzzzzzzzzzzzz')
.catch(err=>console.log(`${err} number`))
.finally(()=>console.log("Promise finally over"))
//output
// odd number
// Promise finally over
Now, I'll write the same Promise using Async & Await. It will be evidently clear which one is better. After that, we'll talk about it's working.
function promiseExample(number) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (number % 2 === 0)
resolve('even');
else
reject('odd');
}, 5000); // 5 seconds delay
});
}
async function oddOrEven(n) {
try {
const result = await promiseExample(n);
console.log(`${result} number`);
console.log("Hurray we did it")
console.log('aaghh I can finally go to sleep now')
console.log('zzzzzzzzzzzzzzzzzzz')
} catch (error) {
console.log(error);
}
}
oddOrEven(5);
As you can see, whatever sequence of code you want to execute after the Promise has either resolved or rejected can be easily put in one block, instead of chaining .then() methods.
Here we have used try & catch block. It's strongly recommended to use, which also means that it's not mandatory. So in case, your Promise only has either resolve or a reject, you needn't write the try & catch block which makes our code more clear. See it for yourself.
async function oddOrEven(n) {
const result = await promiseExample(n);
console.log(`${result} number`);
console.log("Hurray we did it")
console.log('aaghh I can finally go to sleep now')
console.log('zzzzzzzzzzzzzzzzzzz')
}
So the basic idea here is that you can put 'await' in front of a function call to tell the compiler that the return value can wait, keep going ahead. In other words, that the function is asynchronous. One thing to note is that you can use any function asynchronously using the 'await' keyword but in almost all cases 'await' cannot be used without pre-declaring it's parent function 'async'.
In other words, you need to inform the interpreter that some asynchronous task is to be done, during the compile time itself, if that makes any sense.
Keep in mind 🤯👀
async and await must be together.
EXCEPTIONS: JS Modules and Chrome DevTools Console which don't seem to bother you if you are presently learning Async , Await , Promises etc.
async/await only affects Promise receiver.
YES, it has got nothing to do with the Promise body. It affects the way a function is called and things done with it.
You can await any function that returns a Promise
Any function can be converted to async.
⭐All async functions return a Promise.
Error handling with try/catch.