Skip to content Skip to sidebar Skip to footer

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('@')

Solution 1:

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):

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

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

Post a Comment for "How To Pass Promise Result Into Outer Function?"