node.js - 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(() => {});
}
解决方案
我根据自己的理解对原代码做了一些改动。我也怀疑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);
}
推荐阅读
- javascript - 如何修复“未捕获的 ReferenceError:nameCheck 未定义”错误?
- python-3.x - 在 Excel 中创建一个按钮以运行 Python 脚本
- xamarin - 将 UWP 应用上传到 Microsoft Store 时出现验证错误
- javascript - ExcelJS:Angular App中的“未捕获的EvalError:'unsafe-eval'不是以下内容中允许的脚本来源”
- reactjs - 如何使用打字稿修复错误“属性包含在类型'RefObject'上不存在并做出反应?
- javascript - 如何在ajax调用中获取数据属性
- c++ - 错误:非成员函数 'int indice_max(const std::vector
&)' 不能有 cv 限定符 - go - 在结构中匿名/显式嵌入接口
- web-scraping - 为什么soup find all没有显示所有标签
- javascript - 无法在 vuex 操作 Vue.js 中对对象数组进行排序