有人可以解释一下如何通过我的代码在 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();
'收到回复'后再调用下一个函数。解决这个问题的正确方法是什么?我显然不理解 promise 。我正在尝试关注this教程。
最佳答案
Promise 直接内置到 Firebase 中。
var ref = firebase.database().ref();
ref.once('value')
.then(function (result) {
// This only happens after the data has been returned
console.log(result.val());
})
.catch(function (err) {
// This is where errors land
console.log('Error', err.code);
});
Firebase 版本 3 已满足您的需求,因此您无需创建容器 Promise。 :)
关于node.js - Firebase 在 promise 触发之前等待加载数据库数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42520945/