【问题标题】:Promise reject Possibly unhandled Error:承诺拒绝可能未处理的错误:
【发布时间】:2014-05-24 16:31:02
【问题描述】:

我有一个使用数组执行某些操作的函数。 当数组为空时,我想拒绝它。

举个例子

myArrayFunction(){
        return new Promise(function (resolve, reject) {
           var a = new Array();
           //some operation with a
           if(a.length > 0){
               resolve(a);
           }else{
               reject('Not found');
           }           
        };
}

当拒绝操作发生时,我收到以下错误。 可能未处理的错误:未找到

但是,当调用 myArrayFunction() 时,我遇到了以下问题。

handlers.getArray = function (request, reply) {
    myArrayFunction().then(
        function (a) {
            reply(a);
        }).catch(reply(hapi.error.notFound('No array')));
};

拒绝承诺、捕捉拒绝并响应客户的正确方法是什么?

谢谢。

【问题讨论】:

    标签: javascript node.js promise catch-block hapijs


    【解决方案1】:

    .catch 将函数作为参数,但是,您正在传递其他内容。当你不传递一个函数来捕获时,它会默默地什么都不做。愚蠢,但这就是 ES6 所承诺的。

    因为.catch 没有做任何事情,拒绝成为未处理并报告给您。


    修复是将函数传递给.catch

    handlers.getArray = function (request, reply) {
        myArrayFunction().then(function (a) {
            reply(a);
        }).catch(function(e) {
            reply(hapi.error.notFound('No array')));
        });
    };
    

    因为您使用的是全部捕获,所以该错误不一定是 No array 错误。我建议你这样做:

    function myArrayFunction() {
        // new Promise anti-pattern here but the answer is too long already...
        return new Promise(function (resolve, reject) {
                var a = new Array();
                //some operation with a
                if (a.length > 0) {
                    resolve(a);
                } else {
                    reject(hapi.error.notFound('No array'));
                }
            };
        }
    }
    
    function NotFoundError(e) {
        return e.statusCode === 404;
    }
    
    handlers.getArray = function (request, reply) {
        myArrayFunction().then(function (a) {
            reply(a);
        }).catch(NotFoundError, function(e) {
            reply(e);
        });
    };
    

    可以进一步缩短为:

    handlers.getArray = function (request, reply) {
        myArrayFunction().then(reply).catch(NotFoundError, reply);
    };
    

    还要注意以下之间的区别:

    // Calls the method catch, with the function reply as an argument
    .catch(reply)
    

    // Calls the function reply, then passes the result of calling reply
    // to the method .catch, NOT what you wanted.
    .catch(reply(...))
    

    【讨论】:

    • 修复方法是按照您的建议将函数传递给 .catch。第二个选项,即 .catch(NotFoundError, reply);给我以下错误“捕获过滤器必须是错误构造函数或过滤器函数”
    • @juan 你实现了 NotFoundError
    • 是的,我实现了。
    • handlers.getArray = function (request, reply) { var name = request.query.tableId; model.getArray(name) .then(function (dataArray) { reply.file(dataArray[0]); }) .catch(NotFoundError, function(e) { reply(e); }); };函数 NotFoundError(e) { return e.statusCode === 404; }
    • @juan e 可以为空或未定义吗?
    猜你喜欢
    • 2016-11-24
    • 2019-10-27
    • 2016-12-15
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多