承诺拒绝可能未处理的错误:

Jua*_*uan 13 javascript catch-block node.js promise hapijs

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

举个例子

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');
           }           
        };
}
Run Code Online (Sandbox Code Playgroud)

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

但是,当调用myArrayFunction()时,我有以下catch.

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

什么是拒绝承诺,抓住拒绝和回应客户的正确方法?

谢谢.

Esa*_*ija 18

.catch将函数作为参数,但是,您传递的是其他内容.当你没有传递一个函数来捕获时,它将默默无法做任何事情.愚蠢,但这是ES6承诺的.

由于.catch没有做任何事情,拒绝变得无法处理并报告给您.


修复是将函数传递给.catch:

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

因为您正在使用catch all,所以错误不一定是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);
    });
};
Run Code Online (Sandbox Code Playgroud)

哪些可以进一步缩短为:

handlers.getArray = function (request, reply) {
    myArrayFunction().then(reply).catch(NotFoundError, reply);
};
Run Code Online (Sandbox Code Playgroud)

另请注意以下区别:

// Calls the method catch, with the function reply as an argument
.catch(reply)
Run Code Online (Sandbox Code Playgroud)

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