da1lbi3
da1lbi3

Reputation: 4519

Wait on async method in while loop

I have a while loop that loops from one date to the other date. And I want to submit some data to the firebase realtime database.

I want to submit, and wait till the result is back. And then go to the next iteration.

var loop = moment(startDate, 'MM-DD-YYYY').toDate();
var end = moment(endDate, 'MM-DD-YYYY').toDate();

while(loop <= end){

   firebaseAdmin.database().ref('test/data').set({}).then(function(){

   }).catch(function(error) {                 

   });

   const newDate = loop.setDate(loop.getDate() + 1);
   loop = new Date(newDate);  

}

The firebase database uses promises. How can I use them to go further in the loop when the insert is done. And how do I know that everything is done so I can return?

Upvotes: 0

Views: 1672

Answers (2)

Fals
Fals

Reputation: 6839

You can do this recursively, given that you want to continue only if your current request succeeded, like this:

var loop = moment(startDate, 'MM-DD-YYYY').toDate();
var end = moment(endDate, 'MM-DD-YYYY').toDate();

function fetchDataRec(loop, end)
{
  if(loop <= end) return;

  firebaseAdmin.database().ref('test/data').set({}).then(function(){
      if(/*check if you want to continue*/) {
         const newDate = loop.setDate(loop.getDate() + 1);
         loop = new Date(newDate);
         fetchDataRec(loop, end);// loop while refactored to recursion
      }
   }).catch(function(error) {                 

   });
}
fetchDataRec(loop, end);

https://www.sitepoint.com/recursion-functional-javascript/

Upvotes: 2

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174947

There are several ways (you could use .reduce() to create a chain of promises for example)

But the best way these days is to use an async function:

async function insertMany(startDate, endDate) {
  var loop = moment(startDate, 'MM-DD-YYYY').toDate();
  var end = moment(endDate, 'MM-DD-YYYY').toDate();

  while(loop <= end){
    try {
      await firebaseAdmin.database().ref('test/data').set({});
      // bla bla
    } catch (e) {
      // bla bla
    }
    const newDate = loop.setDate(loop.getDate() + 1);
    loop = new Date(newDate);  
  }

  return 'all done!';
}

Or something similar to that, I didn't run it.

Upvotes: 0

Related Questions