简体   繁体   中英

Unexpected reserved word 'await'

I am developing a react-native appliction.

I have a forEach iteration, in which I used await to wait for the result, but I keep getting error: "Unexpected reserved word '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 ). await has to be directly inside an async function,¹ not inside a synchronous function inside an async function.

If you want to use await there, use 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.

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 :

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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