node.js - 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.
解决方案
在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
});
});
推荐阅读
- zsh - 任意父目录的 Zsh 选项卡补全
- css - 如何将 CSS 应用于下拉项
- javascript - 复制按钮功能
- webpack - 捆绑VS。webpack4 中的块
- javascript - 垂直滚动条根据滚动的距离逐位移动
- python - 如何将 CRAFT 语料库中的 XML NER 数据转换为 spaCy 的 JSON 格式?
- marklogic - MarkLogic 中的三元组索引
- python - Tkinter 滚动条仅适用于 create_window
- ios - 将 sender.currentTitle UIButton 文本发送到 PopUpViewController 中的 UILabel,而不是发送到 PopUpViewController
- machine-learning - 用于理解上下文词的自然语言处理技术