使用 async/await 时的 Firebase database.ref().once().forEach() 行为
Firebase database.ref().once().forEach() behaviour when using async/await
我对使用 await 时如何通过 Firebase 实时数据库节点进行迭代感到有点困惑。如何在循环内执行查询?
我的数据结构分为三个层次(notes --> userId --> noteId)
notes:{
-ABC: {
-123:{ ... },
-456:{ ... }
},
-CDE:{
-789:{ ... },
-011:{ ... }
}
}
我的代码使用传统的 .once() 回调函数 - 这有效。
await database.ref('notes').once('value', (topSnap) => {
console.log('topSnap', topSnap.key)
topSnap.forEach((childSnap)=>{
console.log('childSnap', childSnap.key)
childSnap.forEach((notSnap)=>{
console.log('notSnap', notSnap.key)
})
})
})
输出
topSnap notes
childSnap -ABC
notSnap -123
notSnap -456
childSnap -CDE
notSnap -789
notSnap -011
当使用 async/await 我得到另一个结果!
await database.ref('notes').once('value', async (topSnap) => {
console.log('topSnap', topSnap.key)
topSnap.forEach(async (childSnap)=>{
console.log('childSnap', childSnap.key)
userSnap.forEach(async (notSnap)=>{
console.log('notSnap', notSnap.key)
const ref = notSnap.val().refStr
const nestedSnap = await database.ref(ref).once('value')
})
})
})
输出
topSnap notes
childSnap -ABC
notSnap -123
本质上 - 当使用 async / await
时,forEach()
循环不会循环所有值 - 当省略 async/await 时,forEach()
循环按预期工作。
如何在循环内执行查询?亲切的问候 /K
我发现将 .map() 与 Promise.all 结合使用可以让我在使用 async/await 时迭代数组。
const arr = [1, 2, 3];
await Promise.all(arr.map(async (i) => {
await sleep(10 - i);
console.log(i);
}));
// 3
// 2
// 1
console.log("Finished async");
// Finished async
有关该主题的更多信息:
https://advancedweb.hu/how-to-use-async-functions-with-array-foreach-in-javascript/
我对使用 await 时如何通过 Firebase 实时数据库节点进行迭代感到有点困惑。如何在循环内执行查询?
我的数据结构分为三个层次(notes --> userId --> noteId)
notes:{
-ABC: {
-123:{ ... },
-456:{ ... }
},
-CDE:{
-789:{ ... },
-011:{ ... }
}
}
我的代码使用传统的 .once() 回调函数 - 这有效。
await database.ref('notes').once('value', (topSnap) => {
console.log('topSnap', topSnap.key)
topSnap.forEach((childSnap)=>{
console.log('childSnap', childSnap.key)
childSnap.forEach((notSnap)=>{
console.log('notSnap', notSnap.key)
})
})
})
输出
topSnap notes
childSnap -ABC
notSnap -123
notSnap -456
childSnap -CDE
notSnap -789
notSnap -011
当使用 async/await 我得到另一个结果!
await database.ref('notes').once('value', async (topSnap) => {
console.log('topSnap', topSnap.key)
topSnap.forEach(async (childSnap)=>{
console.log('childSnap', childSnap.key)
userSnap.forEach(async (notSnap)=>{
console.log('notSnap', notSnap.key)
const ref = notSnap.val().refStr
const nestedSnap = await database.ref(ref).once('value')
})
})
})
输出
topSnap notes
childSnap -ABC
notSnap -123
本质上 - 当使用 async / await
时,forEach()
循环不会循环所有值 - 当省略 async/await 时,forEach()
循环按预期工作。
如何在循环内执行查询?亲切的问候 /K
我发现将 .map() 与 Promise.all 结合使用可以让我在使用 async/await 时迭代数组。
const arr = [1, 2, 3];
await Promise.all(arr.map(async (i) => {
await sleep(10 - i);
console.log(i);
}));
// 3
// 2
// 1
console.log("Finished async");
// Finished async
有关该主题的更多信息: https://advancedweb.hu/how-to-use-async-functions-with-array-foreach-in-javascript/