【发布时间】:2017-07-20 03:27:07
【问题描述】:
有人可以用我的代码解释如何在 Firebase 中使用 Promise:
var p = new Promise(function(resolve, reject) {
var data=null;
var ref = db.ref("/");
ref.once("value", function(snapshot) {
data = snapshot.val();
});
data.onload = function() {
console.log(data+" onload");
if (data!=null) {
resolve('Success!');
}
else {
reject('Failure!');
console.log('failed');
}
}
});
p.then(function() {
/* do something with the result */
console.log(data+" done");
}).catch(function() {
/* error :( */
console.log("error");
});
我想等到收到data = snapshot.val(); 的“回音”,然后再调用我的下一个函数。这样做的正确方法是什么?我显然不理解承诺。我正在尝试关注this 教程。
【问题讨论】:
-
查看您的代码,这是您需要重温的firebase!忽略promise代码,其余代码看起来完全错误
-
我的意思是,您的
var p可以简单地是var p = db.ref("/").once("value");- 因为once返回一个承诺! ...然后是p.then(function(result) { ... do something with the result ...})
标签: node.js firebase firebase-realtime-database promise onload