I seem to be really confused as to how async and await is supposed to work here. I am trying to get this forEach function to occur before the console.log and res.json. Unfortunately, even when attaching async and await, it is the last thing to occur.
// Setting tags
const tags = ["1", "2", "3"];
app.get("/api/posts", async (req, res) => {
try {
tags.forEach(async function (tag) {
const response = await fetch(api_url + "?tags=" + tag);
const response_1 = await response.json();
console.log(tag);
await api_json.push(response_1);
});
}
catch (error){
console.log(error);
}
console.log(api_json);
res.json(api_json);
});
And the output:
[]
1
2
3
I am not sure how else to change the order of which these functions can occur. Any help would be appreciated. Thanks.
awaitmakes it look like synchronous code, but the callback you pass toforEachis still asynchronous. YourforEachis not, so it launches them immediatly, one after the other, not caring about the previous ones fullfilling or not. You may want to replace it with a regularforloop and useawaitdirectly inside of it