访问Node.js中其他promise函数中的firebase防火promise局部变量-避免全局

Access firebase fireproof promise local variables in other promise functions in Node.js- avoid global

本文关键字:promise 局部变量 全局 防火 js Node 其他 函数 访问 firebase      更新时间:2023-09-26

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

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的新手。所以请告诉我这种方法是否正确:)

工作代码:

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