繁体   English   中英

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

[英]Uncaught SyntaxError: await is only valid in async function in async function

异步函数中调用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);

    }
});

getRevenueByID本身不是异步函数。

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

所以让它异步:

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

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

await getRevenueByID(ID_Array);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM