发生未处理的承诺拒绝警告

Unhandled Promise Rejection Warning Occured

我想创建产品类别,所以我在 productController class 数据库调用 productCatService class 中处理它。我为此添加了 JS promise。现在它给出了以下错误。

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.

切勿在没有 try/catch 的情况下使用 await。您不必 try/catch every await,但在调用堆栈的某处需要有一个 try /catch块。

这里不需要try/catch,只需要returnProductCategory.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);
    }
}

还有don't use new Promise() for operations that already are promises。继续使用你已经拥有的承诺。围绕现有承诺包装 new Promise() 是无用膨胀的来源,它可能会引入细微的错误。避免。