首页 > 解决方案 > Promise is not working correctly with Firebase

问题描述

I have the following code:

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
});

I want to query the firebase database, and for each snapshot, add the val to an array.

I do not fully understand the idea of promises, hence why this isn't working.

Could somebody offer some explanation or an example on why this is not working/how to fix it.

I thought it would add a promise each time it gets the val and then log the values when all the promise have been added.

标签: node.jsfirebasefirebase-realtime-databasepromise

解决方案


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
    });
});

推荐阅读