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 Answers 3
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);
}
}
3 Comments
async can stay where it was. For clarity I added the function wrapper that you had also in my answer.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
This should work
const myfunction = () => {
[1,2,3].map(async (item) => {
const endpoint = "/api/";
await apiService(endpoint, "POST", item)
.then((r) => console.log(r))
});
};
.map()might be an overkill. Can use simpleforloop orfor (item of array) {..}.