0

I have two functions on my backend that essentially do the following:

const function2 = async(var1, var2, var3, var4) => {
  var x = await function1(var1);
  console.log(x);
}
var function1 = async function (var1){
  var array = [];
  var1.forEach(async function(val){
    try{
      smallarr = await Item.find({
        val:val.x
      })
      array.push(smallarr);
    }
  })
  console.log(array);
  return array;
}

However, the log statement in the function2 is getting called before the log statement in function1. I'm going off of the following example from an old StackExchange thread

Example screenshot

What is going wrong in my code? What am I not understanding about async/await? I can provide the actual code instead of the cute example, but they're pretty big functions.

0

1 Answer 1

2

The forEach call is not waiting, its callback is an async function that returns promises, but those are not awaited. Its return value is going into the void. By consequence, console.log(array); is executed before the array is populated with values.

You can fix this by using a normal for loop. NB: a try without a catch is not very useful (and would need a finally), so you could just leave that out.

for (let val of var1) {
    smallarr = await Item.find({ val:val.x })
    array.push(smallarr);
}
Sign up to request clarification or add additional context in comments.

4 Comments

You can add the async keyword to the variable and it will work: myArray.forEach(async x => await DBModel.create({something: x}))
@Daniel, you just repeat the code-pattern of the Asker, and the problem associated with it: the forEach call will not await the promises that are created in the callback given to it. My answer actually explains this, so I think you missed the point.
It does seem to be waiting, and it does work. I think you could give it a test.
No, Daniel, it doesn't work reliably. That's why the Asker asked the question -- because it doesn't (always) work like that. forEach is synchronous.

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.