【问题标题】:Access firebase fireproof promise local variables in other promise functions in Node.js- avoid global在 Node.js 的其他 Promise 函数中访问 Firebase Fireproof Promise 局部变量 - 避免全局
【发布时间】:2016-04-05 05:16:11
【问题描述】:

以下是访问 firebase 数据的工作代码。它使用全局变量“数据”数组将其发送到最终回调函数。 但我不想声明全局变量。那么无论如何我可以将我的数据传递给它之后的每个回调吗?下面是代码。

var data = {};

getData('myKey', function(){
 console.log("myCompleteData: "+ data); //both Id and finalData 
});

var getData= function(key,callback) {
    return fireproof.child("data").child(key)
    .then(CUSTOM_getData)
    .then(callback)
}

function CUSTOM_getData(snapshot) {

        var id= snapshot.val().id;
        data.id= id;

  return {
    then: function(callback) {

    fireproof.child("otherData").child(data.id)
    .then(CUSTOM_getSomethingFromId)
    .then(callback)
      }

  };
}

function CUSTOM_getSomethingFromId(snapshot) {

            var finalData = snapshot.val().finalData;
            data.finalData = finalData;

      return {
        then: function(callback) {

        callback(data);
          }  
      };
}

我是 Node.js 的新手。所以请让我知道这种方法是否正确:)

【问题讨论】:

  • 你为什么要做出自己的承诺:O?
  • 这样我就可以将变量传递给之前的回调。但我知道这种方法是不正确的。我已经解决了这个问题。请在下面查看我的代码。 P.S:我是 Node.js 的新手
  • 您的“新代码”仍然不正确。不要滚动你自己的 Promise 实现,这真的很难——例如,如果你的 Promise 被传递到某个调用 then 回调的地方,并以 Promise 作为其返回值——你的代码行为不正确。即 - 如果你滚动 then 你必须滚动一个完整的 promise impl。
  • 你能帮我看看下面的代码吗?

标签: javascript node.js firebase promise asynccallback


【解决方案1】:

工作代码:

var getSomeData = function(key,callback) {

    var data = {};

    fireproof.authWithCustomToken(nconf.get('config:someToken')).then(function(){

        return fireproof.child("data").child(key)

    }).then(function(snapshot){

            data.id= snapshot.val().id;

            return fireproof.child("otherData").child(data.id)

    }).then(function(snapshot){

            data.finalData = snapshot.val().finalData;

            callback(data);

    }, function(error){
            console.log('Error: '+error);
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    相关资源
    最近更新 更多