javascript - promise 拒绝可能未处理的错误 :

标签 javascript node.js promise catch-block hapi.js

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

举个例子

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')));
};

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

谢谢。

最佳答案

.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(...))

关于javascript - promise 拒绝可能未处理的错误 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23838847/

相关文章:

javascript - 如何将附加的 html 保存到文档中?

node.js - 服务器发送的事件在简单快速 SSE 的 chrome devtools 中显示为空白

node.js - Nodejs解析最小值和最大值返回错误值

javascript - 每个 JS : what's the promises equivalent of async.?

javascript - 如何在没有延迟反模式的情况下将 jQuery $.ajax 调用转换为 Bluebird promise

javascript - 如何在 Node.js 中使用 mongoose.Schema 添加特定长度的数组?

javascript - 三星智能电视应用程序的完整视频应用程序源代码

javascript - AJAX POST 请求中的 HTTP 错误 400

javascript - promise -如何处理已知错误

javascript - 在 Javascript/Jquery 中对对象数组进行子集化和编辑