Leem.fin
Leem.fin

Reputation: 42602

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

Upvotes: 2

Views: 2385

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074355

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.

Upvotes: 5

Related Questions