首页 > 解决方案 > NodeJS:为什么这段代码会抛出警告?

问题描述

我有以下代码,它可以工作,但仍然会引发警告。我在节点 v12 中运行。

(node:15985) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)

这是循环的源代码,谢谢:

const links = await knex('links').where('active', true);
const links = await knex('links').where('active', true).catch((e) => console.log(e)) // does not work neither

for (let index = 0; index < links.length; index++) {
  const element = links[index];
  console.log('Running with', index, element.uri);

  (async () => {
    try {
      const { statusCode } = await got({
        url: `${element.protocol}://${element.uri}:${element.port}`,
        method: 'GET',
        timeout: 5000
      })

      const check = {
        statusCode: statusCode,
      }

      await knex('checks').insert(check);
    } catch (error) {
      const check = {
        status: 'error',
      }

      await knex('checks').insert(check);
    }
  })().catch(() => {});
}

标签: node.jspromiseasync-await

解决方案


我根据自己的理解对原代码做了一些改动。我也怀疑await knex('checks').insert(check);是未处理的承诺的问题。所以我添加了一个 try & catch 来处理它。finally不是必需的。我只是想让流程更清楚一点。我希望它能解决问题,至少提供一些想法。

// assign the async salad to a const to make the flow a bit more clear
const fetchData = async () => {
  try {
    let check;
    const { statusCode } = await got({
      url: `${element.protocol}://${element.uri}:${element.port}`,
      method: 'GET',
      timeout: 5000
    })
    check = {
      statusCode: statusCode,
    };
  } catch (error) {
    check = {
      status: 'error',
    }
  } finally {
    // use a try catch to handle the potential async call
    try {
      await knex('checks').insert(check);
    } catch {
      throw new Error('Error')
    }

  }
};

// if await knex('checks').insert(check) fails, we can catch the error it throws 
try {
  fetchData()
} catch (erroe) {
  console.log(error);
}


推荐阅读