如何将promise结果传递给外部函数?

时间:2017-03-16 10:28:47

标签: javascript callback promise

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];
    });
}

我希望readData函数返回snapshot.val()[field],但Promise是异步的。我怎么解决这个问题?

1 个答案:

答案 0 :(得分:2)

您所做的完全正确:从then回调中返回,并从then返回调用readData的结果。承诺then创建后会使用该值自行解决,使用readData的来电者会在then回调中看到它。

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

这是一个示例(使用setTimeout来模拟数据库操作):

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);
});