简体   繁体   English

意外的保留字“等待”

[英]Unexpected reserved word 'await'

I am developing a react-native appliction.我正在开发一个 react-native 应用程序。

I have a forEach iteration, in which I used await to wait for the result, but I keep getting error: "Unexpected reserved word 'await' ".我有一个 forEach 迭代,在其中我使用 await 来等待结果,但我不断收到错误消息:“意外的保留字 'await'”。 I don't understand why?我不明白为什么?

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)
    }
  }

Because the function it's in isn't an async function, it's a non- async function (the callback to forEach ).因为它所在的 function不是async function,所以它是非async function( forEach的回调)。 await has to be directly inside an async function,¹ not inside a synchronous function inside an async function. await必须直接async function 内,¹而不是在async function 内的同步 function 内。

If you want to use await there, use for-of :如果您想在那里使用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);
    }
};

That way, the await is in the async function.这样, await就在async function 中。

The above does the deletions in series (one after the other), which seemed to me to be what you wanted.以上是连续删除(一个接一个),在我看来这就是你想要的。 But just in case, you can do the operations in parallel using map and Promise.all :但以防万一,您可以使用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);
    }
};

¹ Or at the top level of a module, in environments that support top-level await . ¹ 或者在模块的顶层,在支持顶层await的环境中。

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

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