最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't process Firebase acquired values with async and Foreach - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 11

You 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)
    }
 }
发布评论

评论列表(0)

  1. 暂无评论