[英]Unhandled promise rejection when trying to throw error in async function
I am implementing a piece of code which goes through project's build and checks if there are multiple pages with featured: true
.我正在实现一段代码,它通过项目的构建并检查是否有多个页面具有
featured: true
。 If that is a case, I want to throw an error, so that qa
job in a pipeline would fail.如果是这种情况,我想抛出一个错误,这样管道中的
qa
作业就会失败。 Everything would work fine but I am getting:一切都会正常工作,但我得到:
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()
this is my code:这是我的代码:
/* eslint-disable no-restricted-syntax */
const fs = require('fs');
const findInDir = require('./utils/findInDir');
(async () => {
const dir = './public/page-data/blog';
const fileRegex = /.*/;
const allFiles = findInDir(dir, fileRegex);
let result = 0;
for (const file of allFiles) {
try {
// eslint-disable-next-line no-await-in-loop
const data = await fs.promises.readFile(file);
const obj = JSON.parse(data);
if (obj.result.pageContext.featured === true) {
result += 1;
}
} catch (err) {
// noop
}
}
if (result > 1) {
throw new Error('There are multiple featured blog posts, please fix.');
}
})();
How can I throw an error in async function?如何在异步 function 中引发错误?
You can error can be handled with a catch block, like this:-您可以使用 catch 块处理错误,如下所示:-
/* eslint-disable no-restricted-syntax */
const fs = require('fs');
const findInDir = require('./utils/findInDir');
(async () => {
const dir = './public/page-data/blog';
const fileRegex = /.*/;
const allFiles = findInDir(dir, fileRegex);
let result = 0;
for (const file of allFiles) {
try {
// eslint-disable-next-line no-await-in-loop
const data = await fs.promises.readFile(file);
const obj = JSON.parse(data);
if (obj.result.pageContext.featured === true) {
result += 1;
}
} catch (err) {
// noop
}
}
if (result > 1) {
throw new Error('There are multiple featured blog posts, please fix.');
}
})().catch((e) => {
console.log(e);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.