0

I'm learning about Cloud Firestore (coding on Nodejs/Express - restfull api). I'm having trouble with async and await. According to the code below, the order of appearance is Step B, Step A. So the output value of restaurants is empty. How to make the order appear as Step A, Step B

Thank you.

async function getRestaurants_Detail(snapshot, res) {
  var restaurants = [];
  
  snapshot.forEach( async (doc) => {
    let newRestaurant = await doc.data();
    var cuisines = [];
    if (newRestaurant.cuisineListRef) {
      for (var i = 0; i < newRestaurant.cuisineListRef.length; i++) {
        const snapShotCuisine =await newRestaurant.cuisineListRef[i].get();
        const title = snapShotCuisine.data().title;
        cuisines.push(snapShotCuisine.data());
      }
    }
    restaurants.push({
      id: doc.id,
      title: newRestaurant.title,
      content: newRestaurant.content,
      address: newRestaurant.address,
      cuisines,
    });
    debugApp("Step A");
    debugApp(restaurants);
  })
  debugApp("Step B");
  debugApp(restaurants);
  return ApiSuccess.send(res, { restaurants: restaurants });
}
async getRestaurants(req, res, next) {
    try {
      const restaurantsRef = db.collection("restaurants");
      const snapshot = await restaurantsRef.get();
      return !snapshot.empty ? getRestaurants_Detail(snapshot,res) : ApiSuccess.send(res, { restaurants: [] });
    } catch (err) {
      console.log(err);
      return next(
        ApiError.internal_500(
          "The restaurants you were looking for do not exist",
          err
        )
      );
    }
  }
John A
  • 11
  • 1
  • You could take a look at the .then() function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then – Anes Sep 23 '22 at 11:45
  • 1
    `async` will not really work with `foreach`. Either convert it to `for loop`, either to `.map() + Promise.all()`. You can take a look at this [question](https://stackoverflow.com/questions/73779678/async-await-with-firebase-storage/73779732#73779732) as an example. – Sergey Sosunov Sep 23 '22 at 11:51
  • 1
    Either use `Promise.all()` or `for` loop for this scenario. `async/await` does not work with `foreach` – Drashti Kheni Sep 23 '22 at 12:01

1 Answers1

1
let myPromises = []

snapshots.forEach((...)=>{
    ...
    myPromises.push(promise)
})

await Promise.all(myPromises)
Tiago Bértolo
  • 3,874
  • 3
  • 35
  • 53