-1

Can someone please explain to me why the code below executes the "F" alert first , then the "S' and "V' ALERTS.

var status = ' ';
  database.ref('housekeeping/ongoing').once('value', function(snapshot){
    alert(status + "S");
    status = snapshot.val();
    alert(status + "V");
  });
  alert(status + "F");
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
udacha
  • 1
  • 1

2 Answers2

1

once() is asynchronous and returns immediately, before the query is complete. The callback you provide to it will be executed some time later.

All Firebase APIs are asynchronous, and this is very common in JavaScript. You should also know that once() also returns a promise, and that promise is a better way to handle the results of asynchronous calls. It's very important in modern JavaScript programming to understand how promises work.

I suggest reading this blog on why the Firebase APIs are asynchronous.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
1

As you can see in the documentation, once is an asynchronous call. This means that the code will continue with synchronous tasks until the data has been retrieved. Then, the code within you callback will be executed.

To make the 'S' and 'V' alerts come up first, you will need to make use of async/await:

async function getDatabaseData() {
  const snapshot = await database.ref('housekeeping/ongoing').once('value');
  alert(status + "S");
  status = snapshot.val();
  alert(status + "V");
  alert(status + "F");
}

More information about async/await

Titulum
  • 9,928
  • 11
  • 41
  • 79