等待所有 firebase 调用完成 map 功能

Sor*_*gim 5 javascript firebase react-native firebase-realtime-database

我正在获取我的用户数据,并且为每个用户多次调用 map 函数。我想等到所有数据都被推送到数组,然后操作数据。我尝试使用 Promise.all() 但它没有用。如何在继续之前等待此地图功能完成?

不用说,user_list_temp在 Promise.all() 中打印时数组是空的。

 const phone_list_promise_1 = await arrWithKeys.map(async (users,i) => {
      return firebase.database().ref(`/users/${users}`)
          .on('value', snapshot => {
              user_list_temp.push(snapshot.val());
              console.log(snapshot.val());
            })
        }
  );

Promise.all(phone_list_promise_1).then( () => console.log(user_list_temp) )
Run Code Online (Sandbox Code Playgroud)

我将代码更改为此,但仍然得到错误的输出

Promise.all(arrWithKeys.map(async (users,i) => {
      const eventRef = db.ref(`users/${users}`);
      await eventRef.on('value', snapshot => {
        const value = snapshot.val();
        console.log(value);
        phone_user_list[0][users].name = value.name;
        phone_user_list[0][users].photo = value.photo;
      })
      console.log(phone_user_list[0]); 
      user_list_temp.push(phone_user_list[0]);
    }

  ));
    console.log(user_list_temp); //empty  array
}
Run Code Online (Sandbox Code Playgroud)

Dac*_*nny 1

如果我正确理解您的问题,您可能会考虑修改代码以使用常规for..of循环,并为每个用户提供一个嵌套的承诺,该承诺在该用户的快照/值可用时解析,如下所示:

const user_list_temp = [];

/*
Use regular for..of loop to iterate values
*/
for(const user of arrWithKeys) {

    /*
    Use await on a new promise object for this user that
    resolves with snapshot value when value recieved for
    user
    */
    const user_list_item = await (new Promise((resolve) => {

        firebase.database()
        .ref(`/users/${users}`)
        .on('value', snapshot => {

            /*
            When value recieved, resolve the promise for
            this user with val()
            */    
            resolve(snapshot.val());
        });
    }));

    /*
    Add value for this user to the resulting user_list_item
    */
    user_list_temp.push(user_list_item);
}

console.log(user_list_temp);
Run Code Online (Sandbox Code Playgroud)

这段代码假设封闭函数被定义为带有async关键字的异步方法,看到await关键字在循环中使用for..of。希望有帮助!