How to pass promise result into outer function?

function readData(field) {
    var profileDatabase = firebase.database();
    var user = firebase.auth().currentUser;
    var name = user.email.substring(0, user.email.indexOf("@"));
    return profileDatabase.ref('/users/' + name + 'id').once('value').then(function (snapshot) {
        return snapshot.val()[field];
    });
}

I want the readData function to return snapshot.val()[field], but Promise is asynchronous. How can I resolve that?

Upvotes: 3

Views: 2056

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

What you've done is exactly right: Return it from the then callback, and return the result of calling then from readData. The promise then creates will resolve itself with that value, and the caller using readData will see it in their then callback.

readData(field).then(function(value) {
    // Here, `value` is the value from `snapshot.val()[field]`
});

Here's an example (using setTimeout to simulate the database operation):

function fakeDatabaseOperation() {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve({
        val: function() {
          return {foo: "bar"};
        }
      });
    }, 500);
  });
}
function readData(field) {
    /*
    var profileDatabase = firebase.database();
    var user = firebase.auth().currentUser;
    var name = user.email.substring(0, user.email.indexOf("@"));
    */
    return fakeDatabaseOperation().then(function (snapshot) {
      console.log("Got snapshot here");
      return snapshot.val()[field];
  });
}

readData("foo").then(function(val) {
  console.log("Value here: " + val);
});

Upvotes: 3

Related Questions