Nodejs等到异步映射功能完成执行

时间:2020-10-31 13:31:25

标签: node.js arrays asynchronous

我有一个数组映射,完成映射后需要执行一些代码。

这是数组映射代码

    studentList.map( async index => {
      try{
        const student = await User.findOne({indexNumber: index})
        if (student == null) {
          emptyStudents.push(index)
        }
      }

      catch(err){
        console.log(err)
      }
    })

我该怎么做?由于这是异步的,因此无法找到解决方案。

3 个答案:

答案 0 :(得分:1)

您可以使用地图返回承诺,然后在完成承诺后在地图之外将其推入数组-

const studentPromises = studentList.map( async index => {
    return User.findOne({indexNumber: index})
})

const studentResults = await Promise.all(studentPromises)

studentResults.forEach((student) => {
    if (student == null) {
        emptyStudents.push(index)
    }
})

答案 1 :(得分:1)

await Promise.all(studentList.map( async index => {
  try{
    const student = await User.findOne({indexNumber: index})
    if (student == null) {
      emptyStudents.push(index)
    }
  }
}))

答案 2 :(得分:0)

您可以尝试使用Promise包装数组映射(并在async函数中运行它):

await new Promise((resolve, reject) => {
  studentList.map( async index => {
    try{
      const student = await User.findOne({indexNumber: index})
      if (student == null) {
        emptyStudents.push(index)
      }
      if (studentList.length - 1 === index) {
        resolve();
      }
    }

    catch(err) {
      console.log(err);
      reject(err);
    }
  })
});

// YOUR CODE HERE
相关问题