0

The function is intended to loop over an array and POST each value in the array to database. I got error if I use async await function.

Error : Can not use keyword 'await' outside an async function

 const myfunction = async () => {
    [1,2,3].map((item) => {
      
      const endpoint = "/api/";

      await apiService(endpoint, "POST", item)
        .then((r) => console.log(r))
        
    });
  };

The apiservice function use browser fetch function with stored cookie

This might be duplicate of following question Using async await when mapping over an arrays values, but I did not understand it.

3
  • 1
    Your apiService call is inside the map callback, which means you need to change that function to async: .map(async(item) .... ) Commented Jul 17, 2020 at 17:22
  • Is the intent to just loop over the array? .map() might be an overkill. Can use simple for loop or for (item of array) {..}. Commented Jul 17, 2020 at 17:23
  • @ambianBeing I will use as suggested thanks. Commented Jul 17, 2020 at 17:24

3 Answers 3

2

The reason is that await does not occur directly in your async function, but in a function that is passed to .map (which is not async).

Besides, .map is abused here, since you do not return anything in the callback, nor use the array that .map returns.

Just use a for loop instead:

const myfunction = async () => {
    for (let item of [1,2,3]) {      
        const endpoint = "/api/";
        await apiService(endpoint, "POST", item)
            .then((r) => console.log(r))
    }
}

Also, using then is an antipattern here, since await is actually there to avoid using that. So better code it like this:

const myfunction = async () => {
    for (let item of [1,2,3]) {      
        const endpoint = "/api/";
        let r = await apiService(endpoint, "POST", item)
        console.log(r);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Kudos for the clarification.
Where will I put the async key work in the above function as you suggested ?
async can stay where it was. For clarity I added the function wrapper that you had also in my answer.
1
const myfunction =  () => {
    [1,2,3].map( async(item) => { // async should be here
      
      const endpoint = "/api/";

      await apiService(endpoint, "POST", item)
        .then((r) => console.log(r))
        
    });
  };

Comments

1

This should work

 const myfunction = () => {
    [1,2,3].map(async (item) => {
      
      const endpoint = "/api/";

      await apiService(endpoint, "POST", item)
        .then((r) => console.log(r))
        
    });
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.