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

13

我有一个使用数组进行一些操作的函数。

当数组为空时,我希望拒绝执行该函数。

举个例子:

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()时,我有以下catch。
handlers.getArray = function (request, reply) {
    myArrayFunction().then(
        function (a) {
            reply(a);
        }).catch(reply(hapi.error.notFound('No array')));
};

如何正确地拒绝 Promise、捕获拒绝并回应客户端?

谢谢。

1个回答

18

.catch接受一个函数作为参数,但是你把其他的东西传进去了。当你不向catch传递一个函数时,它将静默地失败而不执行任何操作。虽然很傻但这就是ES6 promise的行为。

因为.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);会给我返回以下错误信息:“catch 过滤器必须是一个错误构造函数或过滤器函数”。 - Juan
@juan,你实现了NotFoundError吗? - Esailija
是的,它已经被实现了。 - Juan
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); }); }; function NotFoundError(e) { return e.statusCode === 404; } - Juan
我有一个类似的问题,但是我附加了一个适当的捕获。我尝试了catch(error => {})和catch(function(e){}) - 承诺内部的拒绝一直失败,导致未处理的承诺拒绝,并且承诺内部的其余代码被执行 - 这真的很糟糕... - Moonwalker
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接