What is the correct way to handle nested asynchronous expectations in Node?

Trying to find out the async pattern in Javascript, but it doesn't seem to be waiting for the next line. In the following example, the collection is a request object, not the actual parsed body. Shouldn't await have to wait for the request to complete?

 async function importUsers(endpoint) { const options = { data: search, uri: endpointCollection, headers, } try { const collection = await browser.post(options, (err, res, body) => JSON.parse(body)) // collection is the request object instead of the result of the request const users = await collection.data.forEach(item => parseUserProfile(item)); await users.forEach(user => saveUserInfo(user)) } catch(err) { handleError(err) } } async function parseUserProfile({ username, userid }) { const url = userProfileString(username) try { const profile = await browser.get(url, headers, (err, res, body) => { return { ... } // data from the body }) } catch(err) { handleError(err) } } 
+5
source share
2 answers

Async / Await only works with functions that return (and resolve) a promise.

The following example will be written to the console after 3 seconds, and then continue.

 // Tell the browser that this function is asynchronous async function myFunc() { // Await for the promise to resolve await new Promise((resolve) => { setTimeout(() => { // Resolve the promise resolve(console.log('hello')); }, 3000); }); // Once the promise gets resolved continue on console.log('hi'); } // Call the function myFunc(); 

Without async / await, the output would look like this:

 hi hello 

This will be due to the fact that hi output will be started, and then after 3 seconds a timeout will be executed.

But with async / await, the output is as follows:

 hello hi 

This is because we are waiting for a timeout, then we run the output of hi .

+5
source

await should expect a promise, for an asynchronous callback style function, you can convert it like this:

 new Promise((resolve, reject) => browser.post(options, (err, res, body) => resolve(JSON.parse(body)))) 

For an array, you need to map it to the promises array, then use Promise.all to turn it into an "array promise", for example:

 Promise.all(collection.data.map(item => parseUserProfile(item))) 
+2
source

Source: https://habr.com/ru/post/1268059/


All Articles