hfbachri_
hfbachri_

Reputation: 107

Looping in Asynchronous programming

I'm pretty new to async. programming. I confuse how to do iteration. I'm trying to iterate db queries. And right after the iteration is done I want to redirect user to the home page. Here's my code:

for(var i =0; i < venue_1_split.length; i++){
    pool.query("INSERT INTO peminjaman_venue VALUES (?,?,?,?,?,?,?,?)",
              [id_event, venue_1_split[i], id_google_calendar, 
              waktu_mulai_1, waktu_selesai_1, tanggal_peminjaman_1,  
              tanggal_peminjaman_1, hari_event_rutin],
             function(err, rows, fields){
                if(err) throw err;
    })
}



   //when the iteration is done.
   res.redirect('/');

How to achieve that? Thank you

Upvotes: 0

Views: 34

Answers (1)

Alex Dovzhanyn
Alex Dovzhanyn

Reputation: 1046

You'll want to map over your array instead of doing a for loop. Since this is asynchronous, you'll want to wrap your .map in a Promise.all and call .then to ensure that it awaits all the promises before continuing. Something like this should work for what you're trying to do:

Promise.all(venue_1_split.map(venue => {
  return new Promise((res, rej) => {
    pool.query(
      "INSERT INTO peminjaman_venue VALUES (?,?,?,?,?,?,?,?)",
      [id_event, venue], id_google_calendar, 
      waktu_mulai_1, waktu_selesai_1, tanggal_peminjaman_1,  
      tanggal_peminjaman_1, hari_event_rutin],
      (err, rows, fields) => {
        if(err) rej(err)
        res()
    })
  }
}))
.then(r => res.redirect('/'))
.catch(err => {console.log(err); res.status(500).send()}) // or whatever you want to do with errors

Upvotes: 3

Related Questions