在Node中处理嵌套asynchronous等待调用的正确方法是什么?
试图学习在Javascript中的asynchronous模式,但它似乎没有等待下面的行。 在下面的例子中,集合是请求对象,而不是实际的parsing主体。 是不是await
要求完成?
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) } }
asynchronous/等待仅适用于返回(并parsing)承诺的函数。
以下示例将在3秒后写入控制台,然后继续。
// 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();
没有asynchronous/等待,输出将如下所示:
hi hello
这是因为hi
输出会运行,然后3秒后超时将运行。
但是,使用asynchronous/等待,输出如下所示:
hello hi
这是因为我们等待超时,然后我们运行hi
输出。
await
应该期待一个承诺,对于一个callback风格的asynchronous函数,你可以将其转换为:
new Promise((resolve, reject) => browser.post(options, (err, res, body) => resolve(JSON.parse(body))))
对于一个数组,您需要将其映射到一个promise数组,然后使用Promise.all
将其转换为“数组的承诺”,例如:
Promise.all(collection.data.map(item => parseUserProfile(item)))