javascript - 如何从 Firebase 快照返回数组

标签 javascript node.js firebase

我正在尝试从 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/

相关文章:

javascript - 如何将超链接添加到通过 Leaflet.Draw 创建的 Leaflet 折线?

javascript - 带标签的 continue 语句; for循环

javascript - MongoDB "Failed to query for documents to update ... unable to decode message length: EOF"

javascript - 即使最大宽度设置为 100%,为什么我的 (json) 图像仍超出边框/容器?

node.js - Sequelize 数据库迁移问题

node.js - 使用 MtGox 的流 API 进行身份验证的命令

javascript - 获取从 firebase firestore 返回的文档中的特定字段

javascript - Firestore : Multiple 'array-contains'

java - 如何搜索包含识别文档字段的未知集合?

javascript - Toggle 方法删除文本突出显示,最终阻止 execCommand 更改突出显示的文本颜色