Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
Javascript await in imbricated loop error

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 );
     }
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!