【问题标题】:Nodejs wait until async map function finishes executingNodejs 等到异步映射函数完成执行
【发布时间】:2021-02-13 17:36:21
【问题描述】:

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

这里是数组映射代码

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

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

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

【问题讨论】:

    标签: node.js arrays asynchronous


    【解决方案1】:
    await Promise.all(studentList.map( async index => {
      try{
        const student = await User.findOne({indexNumber: index})
        if (student == null) {
          emptyStudents.push(index)
        }
      }
    }))
    

    【讨论】:

    • 这是正确的,但稍微解释一下会很好,尤其是因为 Promise 一开始很难理解。
    【解决方案2】:

    您可以尝试使用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
    

    【讨论】:

      【解决方案3】:

      您可以使用地图返回承诺,然后当它们完成时,您可以在地图之外推送到您的数组 -

      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)
          }
      })
      

      【讨论】:

        猜你喜欢
        • 2021-03-06
        • 1970-01-01
        • 1970-01-01
        • 2019-11-07
        • 1970-01-01
        • 1970-01-01
        • 2020-09-13
        • 2018-03-27
        • 2019-11-29
        相关资源
        最近更新 更多