未捕获的SyntaxError:await仅在异步函数的异步函数中有效

问题描述 投票:1回答:1

在异步函数中调用getRevenueByID函数,但获取未捕获的SyntaxError。我在这做错了什么?

(async() =>{

try {
    response = await fetch(mainURL);
    data = await response.json();

    console.log(data);
    console.log(data.results[0].title);

    ID_Array = [].concat.apply([], data.results.map(d => d.id))
    console.log(ID_Array);


    getRevenueByID(ID_Array);
} catch (error) {
    console.log(error);
}
})();

getRevenueByID = (arr => {
    for (let i = 0; i < arr.length; i++){
        console.log("ID is: ", arr[i]);
        getRevenueURL = await fetch('someurl' + arr[i] + '?api_key=YOUR_KEY&language=en-US');
        console.log(getRevenueURL);
        // let data = await getRevenueURL.json();
        // console.log(data);

    }
});
javascript asynchronous promise async-await
1个回答
3
投票

getRevenueByID本身不是异步功能。

“await仅在异步函数中有效”表示“直接进入”而不是“从callstack中的某个地方调用”。

所以让它异步:

getRevenueByID = async (arr) => {
    // ...
};

然后等待它回到你所说的地方:

await getRevenueByID(ID_Array);
© www.soinside.com 2019 - 2024. All rights reserved.