Q拒绝承诺,然后成功callback

我在节点应用程序中使用kriskowal Q promise库。 我有代码读取一个文件,然后试图parsing它的一部分到一个Javascript的date对象(我有类似的代码在其他地方试图做一个JSON.parse)。 在这些情况下,我已经阅读并亲自感觉最好的做法是将代码封装在try / catch块中,以避免和潜在的致命的意外。 这里有一些真正的代码与伪代码混合在一起:

var getMonitorTimestamp = function() { return readLogFile() .then( function ok(contents) { //regex to capture dates in format of: 09 Jan 2015 09:42:01 var regex = /[0-9]{2} [\w]{3} [0-9]{4} ([0-9]{2}:){2}[0-9]{2}/g; var timestamp = contents.match(regex)[0]; var date; try { date = new Date(timestamp); return date; } //when I've caught the error here, how do I reject the promise? //this will still return an error to the next success callback in the queue catch(e) { console.error(e); return e; } }, function err(e) { console.error(e); return new Error(); } ); }; exports.sendRes = function(req, res) { getMonitorTimestamp() .then( function yay(data) { //don't want to send an error here res.json({result: data}); }, function boo(e) { res.status(500).json({error: e}); } ); } 

正如你所看到的,在getMonitorTimstamp-> okcallback中拒绝承诺是有用的,因为它失败了。

Q有没有办法做到这一点? 我还没有find任何东西(还)。 还是有不同的模式来处理这种情况?

这实际上在处理错误一节中的q文档中有介绍。

而不是使用.then(success, fail)风格,你会想链接你的处理程序,让成功处理程序throw到失败处理程序。

 readLogFile() .then(function yay(data) { throw "Eek!"; }) .fail(function boo(e) { res.status(500).json({error: e}); }); 

实际上,如果你使用这个结构(在Q文档中讨论过),你不需要在你的函数中捕获exception:

 function a () { return methodThatReturnsAPromise().then(function () { // Exceptions can happen here }) } a() .then(function () { /* Success */ }) .catch(function (err) { /* Error */ }) 

例外将被传播给承诺的接收者。

至于你的代码:

你被覆盖了exception,但是如果你发现了一个错误条件(不是由exception引起的),你可以在你的readLogFile().then(...函数中返回一个新的被拒绝的promisereadLogFile().then(... function:

 var getMonitorTimestamp = function() { return readLogFile() .then(function (contents) { if (<check errors here>) { // Found the error condition return Q.reject('Failed here') } else { // Return the normal result ... return date } }) } 

在代码的最顶层留下一个catch子句:

 exports.sendRes = function(req, res) { getMonitorTimestamp() .then(function (data) { res.json({result: data}) }) .catch(function (e) { res.status(500).json({error: e}) }) }