0

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?

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Does async/await work everywhere? Isn't it just for node v6+?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.