Array#map() 中的异步/等待 [英] Async/Await inside Array#map()

查看:22
本文介绍了Array#map() 中的异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此代码的编译时错误:

I'm getting compile time error with this code:

const someFunction = async (myArray) => {
    return myArray.map(myValue => {
        return {
            id: "my_id",
            myValue: await service.getByValue(myValue);
        }
    });
};

错误信息是:

await 是保留字

为什么我不能这样使用它?

Why can't I use it like this?

我也尝试了另一种方法,但它给了我同样的错误:

I also tried another way, but it gives me same error:

 const someFunction = async (myArray) => {
    return myArray.map(myValue => {
        const myNewValue = await service.getByValue(myValue);
        return {
            id: "my_id",
            myValue: myNewValue 
        }
    });
};

推荐答案

你不能像你想象的那样做,因为你不能使用 await 如果它不是直接在 async 函数.

You can't do this as you imagine, because you can't use await if it is not directly inside an async function.

此处明智的做法是使传递给 map 的函数异步.这意味着 map 将返回一个承诺数组.然后我们可以使用 Promise.all 来获取所有 Promise 返回时的结果.由于 Promise.all 本身返回一个 promise,外部函数不需要是 async.

The sensible thing to do here would be to make the function passed to map asynchronous. This means that map would return an array of promises. We can then use Promise.all to get the result when all the promises return. As Promise.all itself returns a promise, the outer function does not need to be async.

const someFunction = (myArray) => {
    const promises = myArray.map(async (myValue) => {
        return {
            id: "my_id",
            myValue: await service.getByValue(myValue)
        }
    });
    return Promise.all(promises);
}

这篇关于Array#map() 中的异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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