在异步等待中尝试捕获的问题

时间:2019-06-04 13:29:40

标签: javascript node.js ecmascript-6 async-await ecmascript-2017

我正在努力等待异步尝试捕获块几天。

async function executeJob(job) {

  // necessary variable declaration code here

  try {
    do {
      let procedureRequests = await ProcedureRequestModel.find(filter, options);

      // doing process here...

    } while (fetchedCount < totalCount);

    providerNPIIds = [...providerNPIIds];

    // Fetch provider details
    let providerDetails = await esHelper.getProvidersById(providerNPIIds, true);

    try {

      let updateProviderCount = await UserProvider.updateAll(
          {
            userId: userId
          },
          {
            providers: providerNPIIds,
            countByType: providerCountType
          });

      if(updateProviderCount) {
        try {
          let destroyJobId = await  app.models.Job.destroyById(job.idd);
        } catch (e) {
          var err = new QueueError();
          console.log(err instanceof QueueError);
          throw new QueueError();
        }

      }
    } catch (e) {
      logger.error('Failed to update UserProviders  & Count: %O', err);
      throw e;
    }

    executeNextJob();
  } catch (e) {
    if(e instanceof QueueError) {
      console.log('Exiting from process');
      process.exit(1);
    } else {
      console.log('Working Code');
      buryFailedJobAndExecuteNext(job);
    }

  }
}

我的尝试在此异步函数中捕获了吗?

这就是我创建自定义错误类并在全球范围内导出的方式。

// error.js file

class QueueError extends Error {

}

global.QueueError = QueueError;

要求:

故意在

中将job.id更改为job.idd
let destroyJobId = await  app.models.Job.destroyById(job.idd); 

以便我可以捕获错误。 如果有错误,则抛出新创建的自定义Error类。但是抛出QueueError将导致记录

logger.error('Failed to update UserProviders  & Count: %O', err); 

too,即使没有必要在那里捕获错误,因为try块正在工作 如果抛出QueueError,我只想仅在最后一个catch块中捕获错误。

下面是回调版本,我正在将其转换为异步等待状态。

 Updating providersNPIId & category count
     UserProvider.updateAll({userId: userId},
       {
         providers: providerNPIIds,
         countByType: providerCountType,
       }, function(err, data) {
         if (err) {
           logger.error('Failed to update UserProviders  & Count: %O', err);
           // throw new QueueError();
         }
         // Remove countProvider Job
         app.models.Job.destroyById(job.id, function(err) {
           if (err) {
             logger.error('Failed to remove countProvider job: %O', err);

           }
         });
       });

2 个答案:

答案 0 :(得分:2)

您可以在较小的函数中重构代码,这些函数返回一个Promise,您可以在其中本地包装try-catch并对其进行处理。

async function executeJob(job) {

  // necessary variable declaration code here
  try {

    await doProcedure();

    providerNPIIds = [...providerNPIIds];

    // Fetch provider details
    let providerDetails = await esHelper.getProvidersById(providerNPIIds, true);
    const updateProviderCount = await getProviderCount(userId, providerNPIIds, providerCountType);

    if(updateProviderCount) {
        await destroyJobById(job.idd);
    }

    executeNextJob();
  } catch (e) {
    if(e instanceof QueueError) {
      console.log('Exiting from process');
      process.exit(1);
    } else {
      console.log('Working Code');
      buryFailedJobAndExecuteNext(job);
    }
  }
}

async function doProcedure() {
    try {
        do {
          let procedureRequests = await ProcedureRequestModel.find(filter, options);

          // doing process here...

        } while (fetchedCount < totalCount);
    } catch (err) {
        throw err;
    }
}

async function getProviderCount(userId, providerNPIIds, providerCountType) {
    try {
        let updateProviderCount = await UserProvider.updateAll({ userId: userId }, { providers: providerNPIIds, countByType: providerCountType });
        return updateProviderCount;
    } catch (err) {
      logger.error('Failed to update UserProviders  & Count: %O', err);
      throw e;
    }
}

async function destroyJobById(Id) {
    try {
          let destroyJobId = await app.models.Job.destroyById(Id);
    } catch (err) {
          throw err;
    }
}

答案 1 :(得分:0)

这与您拥有的基本相同:

ERROR TypeError: Cannot read property '1' of undefined
    at push../node_modules/jsmpeg/jsmpg.js.window.jsmpeg.push../node_modules/jsmpeg/jsmpg.js.jsmpeg.decodeBlock (jsmpg.js:1452)
    at push../node_modules/jsmpeg/jsmpg.js.window.jsmpeg.push../node_modules/jsmpeg/jsmpg.js.jsmpeg.decodeMacroblock (jsmpg.js:1042)
    at push../node_modules/jsmpeg/jsmpg.js.window.jsmpeg.push../node_modules/jsmpeg/jsmpg.js.jsmpeg.decodeSlice (jsmpg.js:933)
    at push../node_modules/jsmpeg/jsmpg.js.window.jsmpeg.push../node_modules/jsmpeg/jsmpg.js.jsmpeg.decodePicture (jsmpg.js:672)
    at push../node_modules/jsmpeg/jsmpg.js.window.jsmpeg.push../node_modules/jsmpeg/jsmpg.js.jsmpeg.scheduleDecoding (jsmpg.js:179)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:17290)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
    at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (zone.js:498)

我看到的唯一区别是承诺行3的拒绝。所以我想知道是否:

  

let destroyJobId =等待app.models.Job.destroyById(job.idd);

它正确地拒绝了诺言。