承诺拒绝可能未处理错误:
我有一个使用数组做一些操作的函数。 我想在数组为空时拒绝它。
举个例子
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'); } }; }
当拒绝操作发生时,我得到以下错误。 可能未处理错误:未find
不过,当我调用myArrayFunction()时,我有下面的catch。
handlers.getArray = function (request, reply) { myArrayFunction().then( function (a) { reply(a); }).catch(reply(hapi.error.notFound('No array'))); };
拒绝承诺的正确方法是什么,接受拒绝并回应客户?
谢谢。
.catch
接受一个函数作为参数,但是,你传递给别的东西。 当你不通过一个函数来捕捉,它会默默无闻地做任何事情。 愚蠢但是这是ES6承诺的。
由于.catch
没有做任何事情,拒绝成为未处理,并向您报告。
修正是将一个函数传递给.catch
:
handlers.getArray = function (request, reply) { myArrayFunction().then(function (a) { reply(a); }).catch(function(e) { reply(hapi.error.notFound('No array'))); }); };
因为您正在使用catch全部,错误不一定是一个无数组错误。 我build议你这样做:
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(...))