2

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.

1
  • 1
    await makes it look like synchronous code, but the callback you pass to forEach is still asynchronous. Your forEach is 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 regular for loop and use await directly inside of it Commented Jul 2, 2020 at 19:35

2 Answers 2

5

Use for ... of instead of forEach, which is not asynchronous, so you can await each request sequentially.

for(const tag of tags){
    const response = await fetch(api_url + "?tags=" + tag);
    const response_1 = await response.json();
    console.log(tag);
    await api_json.push(response_1);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Zernst Glad to help.
2

First, see how forEach works.

Array.prototype.forEach = function (callback) {
  // this represents our array
  for (let index = 0; index < this.length; index++) {
    // We call the callback for each entry
    callback(this[index], index, this);
  }
};

As you can see, callback is called but we are not waiting for it to be done before going to the next entry of the array.

That is why this occurs.

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.