在 Node.js 中的其他 promise 函数中访问 firebase fireproof promise 局部变量-避免全局
Access firebase fireproof promise local variables in other promise functions in Node.js- avoid global
下面是从 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);
});
}
下面是从 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);
});
}