0

I am using node and mongodb.

getWeekOldMatches = async()=>{
    dates= await getDatesRelative(-7);
    var info = []; 
    let db = await database.db();

    await dates.forEach(async function(date){
    var matchinfo= await database.query(db, "highlight", {"matchDetail.matchSummary.localStartDate": date});
    await info.push(matchinfo);
    // console.log(info);;
    // console.log(matchinfo);
    });
    // console.log(info);
    return info;
}

When using console.log(matchinfo); it returns the desired data, but when using console.log(info); it is always empty.

Nat Riddle
  • 928
  • 1
  • 10
  • 24

2 Answers2

2

First: do not use await without a promise or a thenable object, you get only bad perfomance.

So your code would be:

getWeekOldMatches = async () => {
    const dates = await getDatesRelative(-7)
    var info = []
    let db = await database.db()

    dates.forEach(async function (date) {
        var matchinfo = await database.query(db, "highlight", { "matchDetail.matchSummary.localStartDate": date })
        info.push(matchinfo)
        // console.log(info);;
        // console.log(matchinfo);
    })
    // console.log(info);
    return info
}

Then, the main problem here is the Array.forEach method. As you can read on MDN docs:

forEach expects a synchronous function. forEach does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as forEach callback.

So you must use a for of loop instead (much cleaner to):

getWeekOldMatches = async () => {
    const dates = await getDatesRelative(-7)
    var info = []
    let db = await database.db()

    for (const date of dates) {
        var matchinfo = await database.query(db, "highlight", { "matchDetail.matchSummary.localStartDate": date })
        info.push(matchinfo)
    }

    return info
}

The strangest thing here is that the console.log(info) inside the forEach callback should work anyway, but i can't replicate your code.

Michele Viviani
  • 175
  • 1
  • 7
-2

You specified await for the "dates" variable. Other processes will wait for this process to finish.

change code :

getWeekOldMatches = async()=>{
    dates= await getDatesRelative(-7);
    var info = []; 
    let db = await database.db();

    dates.forEach(async function(date){
       var matchinfo= await database.query(db, "highlight","matchDetail.matchSummary.localStartDate": date});
       info.push(matchinfo);
      // console.log(info);;
      // console.log(matchinfo);
    });
      // console.log(info);
    return info;
}

Note: I'm telling to indicate. you are following an unhealthy path. You can try the Promises.all method instead of these methods.

https://stackoverflow.com/a/58696098/8015757

Promises.all

Onur Özkır
  • 559
  • 3
  • 12
  • as you have specified i hace removed await in front of dates.forEach.... and still empty. (i thought that await will make script wait until forEach complete) – Deepak Kumar Yadav May 28 '21 at 13:47