react-native firebase使用异步/等待获取键数组

时间:2018-09-08 03:48:34

标签: javascript reactjs firebase react-native firebase-realtime-database

我想使用async/await获取指定记录的子项的键,但是它似乎不起作用,我一直在处理未处理的诺言拒绝。我试图遍历快照并获取每个孩子的密钥并将其存储在数组中

这是我尝试过的:

await firebase.database().ref('User-Message/' + this.state.user.id).once('value', async (snapshot) => {
  await snapshot.forEach(user => {
    this.list.push(user.key)
  })
  return key;
})

我也尝试过这种方式:

let db = await firebase.database().ref('User-Message').child(this.state.user.id);

let response = await db.once('value');

let users = await response.forEach(user => {
  console.log(user.key);
  return user.key;
})

如何使用async/await获取一组键?

这是我不断收到的错误

Possible Unhandled Rejection (id: 0): TypeError: undefined is not a function (evaluating '_this.list.push()')

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

/* let users = await response.forEach(user => {
  console.log(user.key);
  return user.key;
})
// YOUR CODE
*/


//you can do in this way

response =[
  {key:123, name:"Overflow"},
  {key:456, name:"Stack"},
]
let userKeys = response.map(user => user.key)
console.log("userKeys", userKeys)