我执行函数后如何发送结果?

时间:2018-08-07 08:45:26

标签: node.js mongodb express

json()我想在发布后从函数发送结果,但是我认为res.json()在我获得函数的结果之前执行,并且每次结果都不确定时。

Game.find({ $or: [{ 'homeTeamName': awayTeamName }, { 'awayTeamName': awayTeamName }] })
          .then(
            function (games) {
              let gamesGuest = games
              let result = testFunc.createCoef(gamesHome, gamesGuest, homeTeamName, awayTeamName)
              res.json(result)
            }
          )
          .catch(err =>
            res.status(404).json('Away no games')
          )
      }
    )

2 个答案:

答案 0 :(得分:0)

您可以尝试使用异步等待

Game.find({ $or: [{ 'homeTeamName': awayTeamName }, { 'awayTeamName': awayTeamName }] })
      .then(
        async function (games) {
          let gamesGuest = games
          let result = await testFunc.createCoef(gamesHome, gamesGuest, homeTeamName, awayTeamName)
          res.json(result)
        }
      )
      .catch(err =>
        res.status(404).json('Away no games')
      )
  }
)

答案 1 :(得分:0)

我不是Nodejs的专家,但我仍然很陌生,但是我认为使用异步执行时,您可以使用Await,因此它将使函数完成然后转到下一行,将会失败,< / p>

因此请尝试在功能之前添加“等待”

Game.find({ $or: [{ 'homeTeamName': awayTeamName }, { 'awayTeamName': awayTeamName }] })
          .then(
           async function (games) {
              let gamesGuest = games
              let result = await testFunc.createCoef(gamesHome, gamesGuest, homeTeamName, awayTeamName)
              res.json(result)
            }
          )
          .catch(err =>
            res.status(404).json('Away no games')
          )
      }
    )