首页 > 解决方案 > 发生未处理的 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.

标签: node.jssequelize.jses6-promise

解决方案


切勿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 会导致无用的膨胀,并且会引入细微的错误。避免。


推荐阅读