3. async functions by default return a promise. That is the reason that we are able to await async functions.
Whenever an async function called, it always returns a Promise.
As far as our code it could be written like this -
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.
The new async/await syntax allows us to still use Promises, but it mainly eliminates the needs for providing a callback to the chained then() methods.
This callback , instead of returning directly from the asynchronous function, just like if it were a synchronous blocking function.
let value = await myPromisifiedFunction();
When we are planning to use await in our function we should mark our function with async keyword (like in c#)
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
1. 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.