React Native 如何利用循环数据查询Firebase实时数据库的等待结果

y4ekin9u  于 2023-03-19  发布在  React
关注(0)|答案(1)|浏览(108)

我尝试过从成员列表中获取每个成员的详细数据,但这并不是最佳的,因为它总是返回undefined,所以我使用settimeout来等待所检索数据的加载时间。
我已尝试使返回等待循环查询的结果数据
验证码:

database().ref(`/group/${groupid}`)
    .on("value", snapshot => {
      let data_1 = snapshot.val();
      let members = '';
      let i = 0;
      for(let memberid in data_1) {
        i++;
        database().ref(`/members/${memberid}`)
        .once("value", snapshot => {
          let data_2 = snapshot.val();
          members += '"'+memberid+'":{"uid":"'+data_2.uid+'","name":"'+data_2.name+'","avatar":"'+data_2.avatar+'"},';
        }) 
      } 
      let duration = parseInt(i)*125;
        setTimeout(() => {    
          let resmembers = '{'+members.slice(0, -1)+'}'; 
          let membersobj = JSON.parse(resmembers);
          return membersobj;
        },parseInt(duration))
      })

如何使返回等待循环的结果而不设置超时。

uxh89sit

uxh89sit1#

您可以使用Promise.all()像这样处理这个问题......我还使用Object.assign()将数组转换为单个对象

database().ref(`/group/${groupid}`).on("value", async snapshot => {
  let data_1 = snapshot.val();
  let memberPromises = [];
  for (let memberid in data_1) {
    let memberPromise = database().ref(`/members/${memberid}`).once("value").then(snapshot => {
      let data_2 = snapshot.val();
      return {
        uid: data_2.uid,
        name: data_2.name,
        avatar: data_2.avatar
      };
    });
    memberPromises.push(memberPromise);
  }
  let members = await Promise.all(memberPromises);
  let membersobj = Object.assign({}, members);
  return membersobj;
});

希望这能有所帮助...

相关问题