我有一个使用数组执行某些操作的函数。 当数组为空时,我想拒绝它。
举个例子
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/