NodeJS:为什么这段代码会引发警告?

时间:2020-06-03 20:10:41

标签: node.js promise async-await

我有以下代码,它可以工作,但仍会发出警告。 我正在Node 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(() => {});
}

2 个答案:

答案 0 :(得分:0)

您有2个诺言,没有任何阻碍:

  • 正如@Phix在评论中所指出的那样,在第一行:

    // On the first line
    await knex('links').where('active', true)
    
  • 在代码结尾的catch块中:

    await knex('checks').insert(check);

答案 1 :(得分:0)

根据我的理解,我对原始代码进行了一些更改。我还怀疑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);
}