0

I'm trying to understand to to imbricate loops in javascript and call an imported async function from an async script and I get an error. It seems like ReadinglogManager.getReadingLogForAPeriod cannot be call with await?

Main code:

var myfunction = async function(req, res, next){
students.forEach(function(s) {
            
            dateobj.forEach(function(d) {
               console.log('Date: '+d.toString())
                let st= new Date();
           
                const rl = await ReadinglogManager.getReadingLogForAPeriod(st,s.uid );

            });

        });
}

From ReadinglogManager:

var getReadingLogForAPeriod = async function(start_date, student_uid){
   
    let db = DatabaseManager.fs.firestore();
    let dataset = [];
    let snapshot = await db.collection('ReadingLog').where('date', '>=', start_date).where('student_uid', '=', student_uid).get();
  //  dataset = await DatabaseManager.snapshot_to_resultset(snapshot);
    await snapshot.forEach(doc => {
        let tdoc=doc.data();
        tdoc.uid=doc.id;
        console.log("DOC: "+JSON.stringify(tdoc));
        dataset.push(tdoc);
    });
    return Promise.resolve(dataset);
}

Thanks

1 Answers1

1

As await can only be used within an async function and the callback function (the function(d) {} part) is not async so such using will result in an error.

Also changing it to async function(d) {} does not solve the problem neither. Because forEach does not expect its callback to be an async function and does not await its asynchronous execution.

So for such cases you should use plain loop instead of forEach, like:

var myfunction = async function(req, res, next){
  for(let n = 0;i<students.length;++i){
     let s = students[n];
     for(let i = 0;i<dateobj.length;++i){
        let d = dateobj[i];
        console.log('Date: '+d.toString())
        let st= new Date();
        const rl = await ReadinglogManager.getReadingLogForAPeriod(st,s.uid );
     }
  }
}
Eddie Deng
  • 1,399
  • 1
  • 18
  • 30