节点异步等待函数执行不按顺序

Node async await function execution not in order

我很困惑。我是 async 的新手,所以我知道我缺少一些基本的东西,但我正在挠头。从我看过的例子来看,我认为我是对的,但是...

下面的代码在模拟时工作正常。但是,当我从 mongo 获取真正的仪表板对象时,我可以看到执行顺序不对。因此,依赖仪表板对象的代码由于 'undefined'.

而失败

相关代码

router.get('/:id?', (req, res) => {
  getDashboardData(req)
})

async function getDashboardData(req) {  
  const dashboardId = await getDashboardId(req)
  const dashboard = await loadDashboard(dashboardId)
  const results = await showResults(dashboardId, dashboard)
}

async function getDashboardId(req) {
  dashboardId = req.params.id.trim()
  // Some other things happen here but ultimately we return a UUID 
  return(dashboardId)
}

async function loadDashboardFromId (dashboardId) {  
  Dashboard.findOne({dashboardId: dashboardId}).then((dashboard) => {
    if (dashboard == null || dashboard.dashboardId == null) {
      throw new Error('No dashboard matched in loadDashboardFromId for dashbardId: ' + dashboardId)
    } else {
      console.log('dashboard within loadDashboardFromId: ' + dashboard)
      return dashboard
    }      
  })
}

async function showResults(dashboardId, dashboard) {
  console.log("dashboardId: " + dashboardId)
  console.log("dashboard within showResults: " + dashboard)
}

控制台输出如下。您可以看到 showResults() 在 loadDashboard() returns:

之前执行
connected to mongo server.
open connection to mongo server.
dashboardId: dbc7e954-c6a7-490f-8d9b-4dd11f11d262
dashboard within showResults: undefined
dashboard within loadDashboardFromId: {
  _id: new ObjectId("6208f552a442468c65987e62"),
  dashboardId: 'dbc7e954-c6a7-490f-8d9b-4dd11f11d262',
  createdDate: 2022-02-13T00:00:00.000Z,
  surveyId: 'b55a58d6-63f1-473e-9a3c-34f5d63af499',
  participantId: '9b274cfe-68ea-4206-9f3c-f2ee309ec4de',
  personalityTotal: new Decimal128("69"),
 // etc }```

不要混淆 then/catchawait。使用一个或另一个。我更喜欢 await:

async function loadDashboardFromId (dashboardId) {  
  const dashboard = await Dashboard.findOne({dashboardId: dashboardId})
  if (dashboard == null || dashboard.dashboardId == null) {
    throw new Error('No dashboard matched in loadDashboardFromId for dashbardId: ' + dashboardId)
  } else {
    console.log('dashboard within loadDashboardFromId: ' + dashboard)
    return dashboard
  }      
}

您可以使用 Promise ... 更多文档 https://www.newline.co/fullstack-react/30-days-of-react/day-15/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve

  async function getDashboardData(req) { 
    var dashboardId;
    var dashboard;
    var promise = new Promise(async function(resolve, reject) {
      dashboardId = await getDashboardId(req)
      dashboard = await loadDashboard(dashboardId)
      if(dashboardId && dashboard){
         resolve(true);
       }
      })
    const results = await showResults(dashboardId, dashboard)
   }