What do you understand by async and await.
1479
18-Jun-2020
Please describe me in details what is async and await and when it is use with suitable images.
Updated on 18-Jun-2020
Nishi Tiwari
18-Jun-20201. when should we use await?
We should use await before the async function call.
2. When should I use async?
We mark a function as an async one so that it can be called with the await keyword.
OR
1. We can use await with any function that returns a promise. The function which we are awaiting doesn't need to be async necessarily.
2. We should use async functions when we want to use the await keyword inside that function. If we are not gonna be using the await keyword inside a function then we don't need to make that function async.
3. async functions by default return a promise. That is the reason that we are able to await async functions.
const getUsers = (ms) => { // There is no need to make this async return new Promise(resolve => setTimeout(resolve, ms)); }; // the function is async as you need to use await inside it export const inindex = async (req, res) => { await getUsers(5000); res.json([ { id: 1, name: 'John Doe', }, { id: 2, name: 'Jane Doe', }, ]); };We can await any promise in an async function. The code after the await will be executed after the promise that we are awaiting finished.
This is a great alternative to the JavaScript callbacks.