提问者:小点点

在Node中处理嵌套异步等待调用的正确方法是什么?[副本]


尝试学习Javascript中的异步模式,但似乎没有等待下面一行。在下面的示例中,集合是请求对象,而不是实际的解析体。不是应该等待请求完成吗?

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)
    }
}

共2个答案

匿名用户

Async/Await只在返回(并解析)承诺的函数上工作。

下面的示例将在3秒后写入控制台,然后继续。

null

// 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();

匿名用户

应该期望一个承诺,对于回调样式的异步函数,您可以像这样转换它:

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

对于数组,需要将其映射到承诺数组,然后使用将其转换为'Promise of array',例如:

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