JavaScript-在返回函数之前,等待所有array.push()完成

JavaScript-在返回函数之前,等待所有array.push()完成,javascript,arrays,object,Javascript,Arrays,Object,我编写了一个在对象上循环的函数,并使用array.pushXYZ将值XYZ附加到数组中。循环完成后,函数返回一个承诺。当我使用myFunction.thenfunctionresponse{console.logresponse[0]}时,我在控制台中没有定义。当我在控制台中键入console.logresponse[0]时,我得到了正确的值。我做错了什么?我认为将值推入数组需要时间,但我不是100%。任何帮助都将不胜感激 我的代码我没有包括定义数据库的代码,但这并不重要,因为从数据库获取信息工

我编写了一个在对象上循环的函数,并使用array.pushXYZ将值XYZ附加到数组中。循环完成后,函数返回一个承诺。当我使用myFunction.thenfunctionresponse{console.logresponse[0]}时,我在控制台中没有定义。当我在控制台中键入console.logresponse[0]时,我得到了正确的值。我做错了什么?我认为将值推入数组需要时间,但我不是100%。任何帮助都将不胜感激

我的代码我没有包括定义数据库的代码,但这并不重要,因为从数据库获取信息工作正常


forEach内部的异步操作不会与外部承诺链链接-请使用map创建承诺数组,然后需要返回一个Promise.all,以便正确链接每个studentsObj生成的承诺。您还应该尽量避免隐式创建全局变量-改用const

试着这样做:

const getChild = (uid) => (
  db.collection("users").doc(uid).get()
  .then(doc => {
    const { students } = doc.data();
    return Promise.all(students.map(student => (
      db.collection("students").doc(student).get()
      .then((res) => res.data())
    )))
  })
);
或者,改用异步函数使代码更平坦:

const getChild = async (uid) => {
  const doc = await db.collection("users").doc(uid).get();
  const { students } = doc.data();
  return Promise.all(students.map(async (student) => {
    const res = await db.collection("students").doc(student).get();
    return res.data();
  )));
};

现在不是调用push的时候,而是调用db.collectionstudents.docstudent.get的时候。这是异步的。在返回之前,您将返回空输出。是否可以使用GETHAREPARTENUSERID执行?是的,调用GESTHAND现在返回一个在所有异步操作都被解决后解决的承诺,如果将答案标记为接受,以表明问题已解决。
const getChild = async (uid) => {
  const doc = await db.collection("users").doc(uid).get();
  const { students } = doc.data();
  return Promise.all(students.map(async (student) => {
    const res = await db.collection("students").doc(student).get();
    return res.data();
  )));
};