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

本文标签: javascriptCan39t process Firebase acquired values with async and ForeachStack Overflow