【问题标题】:Promise is not working correctly with FirebasePromise 无法与 Firebase 一起正常工作
【发布时间】:2019-05-12 08:38:00
【问题描述】:

我有以下代码:

let promises = [];
//Return first promise from DB save to zone_obj list
firebase.database().ref('node-client/images').once('value').then(function(snapshot) {
    promises.push(snapshot.val());
});
Promise.all(promises).then(values => {
    console.log(values); // zone_obj
});

我想查询 firebase 数据库,并且对于每个快照,将 val 添加到数组中。

我不完全理解承诺的概念,因此为什么这不起作用。

有人可以提供一些解释或示例说明为什么这不起作用/如何解决它。

我认为它会在每次获取 val 时添加一个 Promise,然后在添加所有 Promise 后记录值。

【问题讨论】:

  • Promise 推入数组。不是承诺值。 promises.push(firebase.database().ref('node-client/images').once('value')).
  • 从数据库中检索完成后是否会收到“结束”事件?

标签: node.js firebase firebase-realtime-database promise


【解决方案1】:

当在您的代码中调用Promise.all() 时,promises 数组仍然为空,因为firebase.database().ref('node-client/images').once('value') 返回一个 Promise,该 Promise 在成功查询数据库后被解析。

在数组完全填满后尝试调用Promise.all()

let promises = [];
//Return first promise from DB save to zone_obj list
firebase.database().ref('node-client/images').once('value').then(function(snapshot) {
    // Push the promises to the array
    promises.push(snapshot.val());
})
.then(function() {
    // Log the values when all promises are resolved
    Promise.all(promises).then(values => {
        console.log(values); // zone_obj
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2017-12-14
    • 2020-08-19
    • 2013-02-06
    相关资源
    最近更新 更多