To clear a few doubts –
- You can use
await
with any function which returns a promise. The function you’re awaiting doesn’t need to beasync
necessarily. - You should use
async
functions when you want to use theawait
keyword inside that function. If you’re not gonna be using theawait
keyword inside a function then you don’t need to make that functionasync
. async
functions by default return a promise. That is the reason that you’re able toawait
async
functions.
From MDN –
When an async function is called, it returns a Promise.
As far as your code is concerned, it could be written like this –
const getUsers = (ms) => { // No need to make this async
return new Promise(resolve => setTimeout(resolve, ms));
};
// this function is async as we need to use await inside it
export const index = async (req, res) => {
await getUsers(5000);
res.json([
{
id: 1,
name: 'John Doe',
},
{ id: 2,
name: 'Jane Doe',
},
]);
};