node.js - 发生未处理的 Promise Rejection 警告
问题描述
我想创建 Product Categories ,所以我在课堂上的productController
类数据库调用中处理它productCatService
。我为此添加了 JS 承诺。现在它给出了以下错误。
productCatController.js
module.exports.createProductCat = async (request, response)=> {
let result = await productCatService.createProductCat(productCatData);
if (result) {
responseService.successWithData(response, "Product Category Created");
} else {
responseService.errorWithMessage(response, result);
}
}
productCatService.js
module.exports.createProductCat = (productCatData) => {
let productCat = {
name: productCatData.name,
desc: productCatData.desc,
count:productCatData.count,
status : productCatData.status
};
return new Promise((resolve,reject)=>{
ProductCategory.create(productCat).then(result => {
resolve(true);
}).catch(error => {
reject(false)
})
});
}
错误
(node:18808) UnhandledPromiseRejectionWarning: false
(Use `node --trace-warnings ...` to show where the warning was created)
(node:18808) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a p
romise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.
html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:18808) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a no
n-zero exit code.
解决方案
切勿await
在没有try
/的情况下使用catch
。您不必try
/ catch
every await
,但调用堆栈下方的某个地方需要有try
/catch
块。
你不需要try
/这里,只需从...catch
返回承诺ProductCategory.create()
// productCatService.js
module.exports.createProductCat = (productCatData) => ProductCategory.create({
name: productCatData.name,
desc: productCatData.desc,
count: productCatData.count,
status: productCatData.status
});
...但你肯定需要try
/catch
这里,因为这个函数是这个操作的堆栈底部,它负责向调用者表示整体成功或失败。
// productCatController.js
module.exports.createProductCat = async (request, response) => {
try {
await productCatService.createProductCat(productCatData);
responseService.successWithData(response, "Product Category Created");
} catch (err) {
responseService.errorWithMessage(response, err);
}
}
也不要new Promise()
用于已经是promises的操作。继续使用你已经拥有的承诺。包装new Promise()
现有的 Promise 会导致无用的膨胀,并且会引入细微的错误。避免。
推荐阅读
- servlets - WSO2 Rest API 请求与 Java Servlets 应用程序集成
- excel - 从软件导入的文本与写入的文本不同
- visual-studio - 在 Visual Studio 中,如何将“插入/删除断点”命令添加到工具栏或菜单?
- java - 在Java中的子类中过滤掉父类中的记录
- .net-core - Team City 未能构建 Dot Net Core,但手动构建有效
- javascript - 在 Javascript 上本地获取 json 数据
- node.js - 使用 node.js 从 http 读取 MP3
- java - 有什么方法可以简化我编写的程序?(初级程序员)
- sql - 我需要帮助以特定方式完成更新
- php - 调用未定义的方法 mysqli_result::fetch()