Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  80] [ 1]  / answers: 1 / hits: 18357  / 7 Years ago, tue, june 13, 2017, 12:00:00

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?


More From » node.js

 Answers
8

To clear a few doubts -




  1. You can use await with any function which returns a promise. The function you're awaiting doesn't need to be async necessarily.

  2. You should use async functions when you want to use the await keyword inside that function. If you're not gonna be using the await keyword inside a function then you don't need to make that function async.

  3. async functions by default return a promise. That is the reason that you're able to await 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',
},
]);
};

[#57483] Friday, June 9, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breap

Total Points: 606
Total Questions: 96
Total Answers: 108

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
breap questions
Thu, Jun 24, 21, 00:00, 3 Years ago
Wed, Mar 18, 20, 00:00, 4 Years ago
Mon, Oct 7, 19, 00:00, 5 Years ago
;