javascript - 等待所有 firebase 调用完成 map 函数

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

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

不用说,数组 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) )

我把代码改成了这样,但我仍然得到错误的输出

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
}

最佳答案

可以将 async/awaitfirebase 一起使用

这就是我通常制作 Promise.all

的方式
const db = firebase.database();
let user_list_temp = await Promise.all(arrWithKeys.map(async (users,i) => {
    const eventRef = db.ref(`users/${users}`);
    const snapshot = await eventref.once('value');
    const value = snapshot.value();
    return value;
  })
);

这篇文章很好地解释了如何使用 Promise.allasync/await https://www.taniarascia.com/promise-all-with-async-await/

以下是我将如何重构您的新代码片段,这样您就不会混合使用 promisesasync/await

let user_list_temp = await Promise.all(arrWithKeys.map(async (users,i) => {
  const eventRef = db.ref(`users/${users}`);
  const snapshot=  await eventRef.once('value');
  const value = snapshot.val();
  console.log(value);
  phone_user_list[0][users].name = value.name;    // should this be hardcoded as 0?
  phone_user_list[0][users].photo = value.photo;  // should this be hardcoded as 0?
  console.log(phone_user_list[0]); 
  return phone_user_list[0];        // should this be hardcoded as 0?
  })
);
console.log(user_list_temp); 

这是一个使用 fetch 而不是 firebase 的简单示例:

async componentDidMount () {
  let urls = [
    'https://jsonplaceholder.typicode.com/todos/1',
    'https://jsonplaceholder.typicode.com/todos/2',
    'https://jsonplaceholder.typicode.com/todos/3',
    'https://jsonplaceholder.typicode.com/todos/4'
  ];
  let results = await Promise.all(urls.map(async url => {
    const response = await fetch(url);
    const json = await response.json();
    return json;
  }));
  alert(JSON.stringify(results))
}

关于javascript - 等待所有 firebase 调用完成 map 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54524461/

相关文章:

javascript - 如何在发生图像更改事件时显示加载图标。 (没有 jQuery)

javascript - React Native 和 Firebase - Firebase 函数作为引用

mysql - fetch API 总是返回 {"_U": 0, "_V": 0, "_W": null, "_X": null}

javascript - 仅在 Web 浏览器上运行 AWS 应用程序时出现 Expo 错误 (AmplifyI18n)

javascript - 将数组键转换为数字node.js

javascript - React-router v2.0 browserHistory 不工作

javascript - 如何绘制图像()并用新内容替换旧内容?

firebase - Firebase 安全规则中的临时变量

ios - Firebase 无效的位码版本

Firebase 在 React-native-android 上的 Facebook 登录