【问题标题】:Multiple await call error handling in NodeJSNodeJS中的多个等待调用错误处理
【发布时间】:2019-11-06 09:18:46
【问题描述】:

我正在使用 async/await 处理多条记录,并使用 Promise 进行并行处理。请参阅下面的示例代码

  let results = [100,200]
  let promises = results.map(async record => {
   try { 
     return await processingRecords(record);  
   } catch (err) {
   }
  });
  await Promise.all(promises);

async function processingRecords(item) {
 switch (item['#type']) {
    case 'case1':
        await Request1(item)
        await Request2(item)
    break
    case 'case2':
        await Request3(item)
 }
}

但问题是,如果 Request1 出现任何错误,我无法从 Request2 调用中捕获错误如何处理来自两个调用的错误

【问题讨论】:

  • 解决方案很大程度上取决于您要在哪里进行错误处理。整体程序架构/设计可能要求在 processingRecords() 或其调用者中完成。
  • 如果Request1() 抛出一个错误,Request2() 将永远不会被调用,那么您希望如何处理来自它的错误?

标签: node.js ecmascript-6 promise async-await


【解决方案1】:

您可以在此处执行一些操作来保持通话继续进行。捕获 await 语句周围的错误并返回 Request1 和 Request2 的组合结果将起作用:

例如:

async function processingRecords(item) {
    switch (item['#type']) {
        case 'case1':
            let combinedResult = {};
            try { 
                combinedResult.Request1Result = await Request1(item);
            } catch (err) {
                combinedResult.Request1Error = err;
            }
            try { 
                combinedResult.Request2Result = await Request2(item);
            } catch (err) {
                combinedResult.Request2Error = err;
            }
            // Keep the promise chain intact.;
            return combinedResult;
        case 'case2':
            return await Request3(item);
        }
}


let promises = results.map(async record => {
    try { 
        return await processingRecords(record);  
    } catch (err) {
        // Keep the promise chain intact by throwing err here.
        throw err;
    }
});

let overallResult = await Promise.all(promises);
console.log(overallResult);

【讨论】:

  • Case1 保证processingRecords(record) 返回的承诺将遵循其成功路径。捆绑到对象中的错误实际上是数据。调用者需要跳过箍才能处理它们。这本身并没有错,但请记住 case1 和 case2 的行为会有所不同。
【解决方案2】:

你可以试试这个

async function processingRecords(item) {
 switch (item['#type']) {
    case 'case1':
    [req1 , req2] = [await Request1(item),await Request2(item)]
    break;
    case 'case2':
       await Request3(item)
 }
}

【讨论】:

  • 这与简单的req1 = await Request1(item); req2 = await Request2(item); 没有什么不同。你为什么使用数组?
猜你喜欢
  • 2020-05-24
  • 1970-01-01
  • 2018-07-29
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 2014-06-15
  • 1970-01-01
相关资源
最近更新 更多