I think my understanding of it might be affected by my experience with .NET's async/await
, so I'd like some code example:
I'm trying to make a express controller wait 5 seconds before returning the response:
const getUsers = async (ms) => {
var wait = ms => new Promise(resolve => setTimeout(resolve, ms));
await wait(ms);
};
export const index = (req, res) => {
async () => {
await getUsers(5000);
res.json([
{
id: 1,
name: 'John Doe',
},
{ id: 2,
name: 'Jane Doe',
},
]);
};
};
This code doesn't work, the browser keeps loading and loading and never shows a thing.
The getUser
function I built based on this SO answer, and the controller method, based on my (mistaken) understanding of how it works so I'd like some clarification and correction:
1. when should I use await
?
To my understanding, you should use await
before an async
function call. Is this correct? Also, why can I call await before a non-async function that returns a promise?
2. When should I use async
?
To my understanding, you mark a function as an async
one so that it can be called with the await
keyword. Is this correct? Also, [why] do I have to wrap my await getUsers(5000)
call in an anonymous async function?