admin管理员组文章数量:1356413
I want to process the value obtained by Firebase with Forach. To processed in order, async, await was used.
const sleep = time => new Promise(resolve => setTimeout(resolve, time));
async function () {
var snapshot = await firebase.database().ref("/path/").once("value")
snapshot.forEach(async function (childSnapshot) {
await sleep(1000)
console.log(snapshot.val)
})
}
However, as a result only the first item of the first is processed. That is, Foreach is not working. Foreach will work if you remove async, await. How can we make them patible?
I want to process the value obtained by Firebase with Forach. To processed in order, async, await was used.
const sleep = time => new Promise(resolve => setTimeout(resolve, time));
async function () {
var snapshot = await firebase.database().ref("/path/").once("value")
snapshot.forEach(async function (childSnapshot) {
await sleep(1000)
console.log(snapshot.val)
})
}
However, as a result only the first item of the first is processed. That is, Foreach is not working. Foreach will work if you remove async, await. How can we make them patible?
Share Improve this question edited Feb 28, 2019 at 1:36 Doug Stevenson 318k36 gold badges456 silver badges473 bronze badges asked Feb 28, 2019 at 1:19 zenzen 335 bronze badges2 Answers
Reset to default 11You won't be able to use forEach, since it requires that you pass a function, and it won't use the promise returned by it (which is always what an async function returns). Instead, convert the database child nodes into an array and iterate it with for/of:
async function () {
const snapshot = await firebase.database().ref("/path/").once("value")
const array = []
snapshot.forEach(child => array.push(child))
for (const child of array) {
await sleep(1000)
console.log(snapshot.val)
}
}
Also note that the snapshot returned by Firebase isn't an array and can't be iterated with for/of directly. Its forEach method is its own special child node iterator.
I faced a similar problem where the array.push(child) was getting executed only once. Hence adding to Doug's solution we need to do something like this so that the forEach loop does not exit before pleting the entire process:
async function () {
const snapshot = await firebase.database().ref("/path/").once("value")
const array = []
snapshot.forEach((child: any) => {
array.push(child)
return false
})
for (const child of array) {
await sleep(1000)
console.log(snapshot.val)
}
}
本文标签: javascriptCan39t process Firebase acquired values with async and ForeachStack Overflow
版权声明:本文标题:javascript - Can't process Firebase acquired values with async and Foreach - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744058822a2583745.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论