繁体   English   中英

意外的保留字“等待”

[英]Unexpected reserved word 'await'

我正在开发一个 react-native 应用程序。

我有一个 forEach 迭代,在其中我使用 await 来等待结果,但我不断收到错误消息:“意外的保留字 'await'”。 我不明白为什么?

const removeData = async () => {
    try {
      dataArray.forEach((data) => {
        // What is wrong with my 'await' usage here??? It is a async API
        const deletedData = await API.graphql({ query: deleteData, variables: { input: data } });
       
      })
    } catch (err) {
      console.log('error deleting data:', err)
    }
  }

因为它所在的 function不是async function,所以它是非async function( forEach的回调)。 await必须直接async function 内,¹而不是在async function 内的同步 function 内。

如果您想在那里使用await ,请使用for-of

const removeData = async () => {
    try {
        // Does the deletions in series (one after the other)
        for (const data of dataArray) {
            const deletedData = await API.graphql({ query: deleteData, variables: { input: data } });
            // ...presumably use `deletedData` here...
        }
    } catch (err) {
        console.log("error deleting data:", err);
    }
};

这样, await就在async function 中。

以上是连续删除(一个接一个),在我看来这就是你想要的。 但以防万一,您可以使用mapPromise.all并行执行操作:

const removeData = async () => {
    try {
        // Does the deletions in parallel (all running together)
        const deletedDataArray = await Promise.all(dataArray.map(
            data => API.graphql({ query: deleteData, variables: { input: data } })
        ));
        // ...presumably use `deletedDataArray` here...
    } catch (err) {
        console.log("error deleting data:", err);
    }
};

¹ 或者在模块的顶层,在支持顶层await的环境中。

暂无
暂无

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

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