在Node中处理嵌套异步等待调用的正确方法是什么? [英] What is the correct way to handle nested async await calls in Node?

查看:51
本文介绍了在Node中处理嵌套异步等待调用的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to learn the async pattern in Javascript but it doesn't appear that it waits for the following line. In the following example, the collection is the request object and not the actual parsed body. Isn't await supposed to wait for the request to finish?

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


推荐答案

Async / Await仅适用于返回(并解析)承诺的函数。

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

以下示例将编写3秒后进入控制台,然后继续。

The following example will write to the console after 3 seconds, and then continue on.

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

如果没有async / await,输出结果如下:

Without async/await, the output would be as follows:

hi
hello

这是一个没有async / await的例子:

Here is an example without async/await:

// Tell the browser that this function is asynchronous
async function myFunc() {
    // Skip await
    new Promise((resolve) => {
        setTimeout(() => {
            // Resolve the promise
            resolve(console.log('hello'));
        }, 3000);
    });
    // Since await was not used, this will print first
    console.log('hi');
}

// Call the function
myFunc();

这是因为 hi 输出会运行,然后在3秒后运行超时。

This would be because the hi output would run and then after 3 seconds the timeout would run.

但是使用async / await,输出如下所示:

But with async/await, the output looks like this:

hello
hi

这是因为我们等待超时然后我们运行 hi 输出。

This is because we await for the timeout then we run the hi output.

这篇关于在Node中处理嵌套异步等待调用的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆