如何在异常情况下继续执行地图循环?

时间:2020-07-02 12:36:59

标签: javascript

这是我的代码。

async function test(){

try{
   const result = //await "database query1"
   result.map(async item => {
   try{
      //await "database query2"
   }catch(e){
      //If code reaches here the whole map function ends even if there are more item in result 
   }
  }catch(e){
     //handle "database query1"
  }
}

如何继续映射功能,直到所有数组项都结束?

3 个答案:

答案 0 :(得分:3)

您可能正在寻找类似的内容,以在所有项目上并行运行查询2,同时吞下可能发生的任何错误。

async function test() {
  const result = await database.query("query1");
  const results = await Promise.all(
    result.map(async (item) => {
      try {
        return await database.query("query2", item);
      } catch (e) {
        return null; // Maybe log the error?
      }
    }),
  );
  return results;
}

答案 1 :(得分:1)

这似乎是对.map()的滥用。您实际上并没有映射任何内容,也不从函数返回任何内容,也不分配任何结果。看来您只是在寻找循环:

for (let item of result) {
    try {
        // await "database query2"
        // etc.
    } catch(e) {
        // handle the exception in some way
    }
}

只要“处理异常”不涉及结束循环或以任何方式退出堆栈的那一部分,循环就会继续。

答案 2 :(得分:0)

实际上,我之所以面对这个问题,是因为try内部的map的某些查询没有await。我不确定为什么会发生这种情况,但在每种情况下我们都需要等待,它会返回promise以使捕获工作按预期进行。