首页 文章

JavaScript错误处理异步函数传递给reduce

提问于
浏览
1

我将 async 函数传递给数组 reduce 函数 . 捕获传入函数抛出的错误的语法是什么?减少发生在 try catch 块中,它正好捕获其他错误,但是如果传入的函数本身抛出错误,则节点会给我一个 UnhandledPromiseRejectionWarning .

Code:

aFunction = async (anArray) => {
  try {
    const result = await anArray.reduce(async (a, b) => {
      await doSomethingTo(b);
    }, Promise.resolve());

    return result;
  }

  catch (error) {
    winston.error(error);
  }  
}

(Edit) Actual code:

exports.chainedQueryDB = async (queries, finalTask, download) => {
  let client = await pool.connect();
  try {
    winston.info(`Begin chained table query.`);
    // Loop through query array
    const result = await queries.reduce(async (a, b) => {
      await client.query(b);
    }, Promise.resolve());

    if (download) {
      return streamOut(download, client);
    }

    return result.rows;
  }

  catch (error) {
    throw error;
  }

  finally {
    const final = await client.query(finalTask);
    winston.info(`Temp table dropped.`);
    client.release();
  }
}

(Edit) Report:await a; return client.query(b); 替换 await client.query(b) 解决了问题 . 只有 await client.query(b)reduce 似乎1)生成一堆浮动 client.query 调用,即使先前的承诺被拒绝,所有调用都会运行,并且2)导致未处理的承诺拒绝警告 . 使用 await a; return client.query(b); 在第一次拒绝时停止执行,catch块按原先的意图捕获错误 .

2 回答

  • 2

    你需要对累加器中的promise( a 参数)做一些事情 - await 它,通过安装 .catch() 回调来处理它的错误,与 doSomething(b) 同时等待它 . 对于顺序执行,您可以这样做

    async function aFunction(anArray) {
      try {
        return await anArray.reduce(async (a, b) => {
          await a; // make sure the previous query is done
          return doSomethingTo(b);
        }, Promise.resolve());
      } catch (error) {
        winston.error(error);
      }
    }
    

    我会推荐在这里根本不使用 reduce

    async function aFunction(anArray) {
      try {
        let result;
        for (const b of anArray) {
          result = await doSomethingTo(b);
        }
        return result;
      } catch (error) {
        winston.error(error);
      }
    }
    
  • 0

    为避免 UnhandledPromiseRejectionWarning ,您可以将 .catch() 链接到 aFunction() 或使用 .then() 的第二个参数来处理被拒绝的 Promise 或错误 .

    或者,链 .catch()doSomethingTo(b) 调用来处理错误 .

相关问题