异步功能不等待其他功能的答复(带有承诺)

时间:2019-12-30 09:26:35

标签: node.js asynchronous promise async-await es6-promise

考虑以下帖子处理程序:

router.post("/add-claims-to-group", auth, async (req, res) => {

  const { howManyClaims, groupTarget, leads, week } = req.body;


  const success = await leads_helper.addClaimsToAGroup(
    howManyClaims,
    groupTarget,
    leads,
    week
  );
  doMoreStuff();


... more code 


}

处理程序正在调用的函数:

addClaimsToAGroup = async (howManyClaims, groupTarget, leads, week) => {

 var aggregatePromise = getDocsByLeadsPromise().then(targeted_lead_ids => {
      return new Promise((resolve, reject) => {

            ... code with resolve and reject 
      }

 }


  var secondPromise = aggregatePromise.then(result => {
   return new Promise((resolve, reject) => {

            ... code with resolve and reject 
      } 
  }




  var thirdPromise = secondPromise.then( p =>
       return new Promise((resolve, reject) => {

        ...
       }
        ...

      )

   var finalPromise = thirdPromise
      .then(async targetedLeadsForInsert => {

         const new_leads = ....
         await EightWeekGamePlan.insertMany(new_leads);
         ... 
         return 1;


      });
}   

运行线路时:

const success = await leads_helper.addClaimsToAGroup(...);

即使它是异步的,我也一直在等待答案,但是代码永远不会等待最终承诺的答案,而是继续到doMoreStuff();

为什么会这样?

0 个答案:

没有答案