在Array#map()中异步/等待

问题描述 投票:30回答:2

我用这段代码得到编译时错误:

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

错误信息是:

等待是一个保留字

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

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

 const someFunction = async (myArray) => {
    return myArray.map(myValue => {
        const myNewValue = await service.getByValue(myValue);
        return {
            id: "my_id",
            myValue: myNewValue 
        }
    });
};
javascript async-await ecmascript-2017
2个回答
53
投票

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

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

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

8
投票

那是因为map中的函数不是异步的,所以你不能等待它的return语句。它编译了这个修改:

const someFunction = async (myArray) => {
    return myArray.map(async (myValue) => { // <-- note the `async` on this line
        return {
            id: "my_id",
            myValue: await service.getByValue(myValue)
        }
    });
};

Try it out in Babel REPL

所以...如果没有看到你的应用程序的其余部分就不可能给出建议,但是根据你想要做什么,要么使内部函数异步,要么尝试为这个块提出一些不同的架构。

更新:有一天我们可能会等待顶级:https://github.com/MylesBorins/proposal-top-level-await

© www.soinside.com 2019 - 2024. All rights reserved.