我正在尝试从 Firebase 检索一些数据(这非常有效),但我的同事需要我将快照的值作为数组返回,以便他可以在另一个文件中使用它。 据我所知,不可能知道值事件是异步。
举个例子:
function getData() {
let current = [];
qRef.on("value", function (snapshot) { //qRef is the reference to my DB
current = snapshot.val();
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
return current; //expected value is the returned data from the snapshot
}
有没有替代方案? 谢谢。
最佳答案
你是对的,你不能直接返回值,因为它是异步的。
相反,您应该使用 Promises:
function getData() {
return qRef
.once('value')
.then(snapshot => snapshot.val())
.then(value => [ value ])
}
请注意,我使用的是 .once()
而不是 .on()
。 .on()
用于监听变化,.once()
用于按需获取值。此外,.on()
不使用 promise,因为 promise 意味着“一些异步工作会发生,然后你会得到一个结果”。监听一个值可能意味着多次触发回调。
关于javascript - 如何从 Firebase 快照返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51802545/