-2

I have 2 files

//init.js
var x = getMasterList(location);
console.log(x);
console.log("should have printed list");

And

//read.js
function getMasterList(location) {
    var list = [];
   ref.child(company).child("listOfLocations").once("value").then(function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
          var item = childSnapshot.val();
          list.push(item);
        })
    });
    console.log("In function");
    return list;
}

The console's output is

undefined
should have printed list
In function

The problem is, because of javascript's asynchronous nature, it prints out 'x' before assigning it. I've looked at promises and it doesn't seem like it can help me since it didn't change the async behaviour. I've also looked at callbacks and I can't seem to make them work for multiple files.

Any ways of getting around this so that it only prints after 'x' has a value?

Astrodude
  • 3
  • 3

1 Answers1

0

Using callbacks, you can achieve this quite easily.

read.js

function getMasterList(location, callback) {
    var list = [];
    //do stuff
    console.log("In function");
    callback(list);
}

init.js

var x = getMasterList(location, function(x){
    console.log(x);
    console.log("should have printed list");
});
Darryl Huffman
  • 2,499
  • 3
  • 18
  • 40