如何将承诺结果传递给外部函数? [英] How to pass promise result into outer function?

查看:50
本文介绍了如何将承诺结果传递给外部函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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是异步的.我该如何解决?

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

推荐答案

您所做的完全正确:从 then 回调返回它,并返回调用 then的结果来自 readData . then 创建的承诺将使用该值进行自我解析,并且使用 readData 的调用方将在其 then 回调中看到它.

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

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

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

这篇关于如何将承诺结果传递给外部函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆