我正试图中途停止promise链(捕获后)。因此,在第一个承诺中发生错误后,catch会捕获它,但我不希望链继续。我在用蓝鸟。我该怎么做?
getRedirectedURL(url).then(function(url) {
console.log(1);
url = domainCleanse(url);
sql = mysql.format(select, url);
return [ url, mysqlQuery(sql) ];
}).catch(function(error) {
console.log(2);
console.error(error);
socket.emit('error:unreachable', url + ' was unreachable');
}).spread(function(url, rows) {
console.log(3);
if(_.isEmpty(rows[0])) {
socketList.push({
url: url,
ttl: _.now(),
socket: socket,
added: false
});
} else {
socket.emit('done', mapResults(rows[0]));
}
}).catch(function(error) {
console.log(4);
console.error(error);
socket.emit('error', 'We could not reach ' + url + ' at this time.');
});
概括您的示例,它看起来像这样:
promiseToFoo()
.then(promiseToBar)
.catch(failedToFooOrBar)
.then(promiseToFrob)
.catch(failedToFrob)
沿着幸福的道路,你向Foo承诺,然后去Bar,然后去Frob。根据您的描述,您希望将错误Fooing或Barring与错误Frobing分开处理。因此,一个简单的解决方案是将Frob的错误处理嵌入该承诺中。因此,您不是将承诺链接到Frob,而是将承诺链接至Frob并处理Frobing中的错误。类似这样的东西:
promiseToFoo()
.then(promiseToBar)
.catch(function (error) {
failedToFooOrBar(error);
return Promise.reject(error);
})
.then(function (x) {
return promiseToFrob(x).catch(failedToFrob);
});
关键是要确保第一个catch
中的拒绝处理程序在链离开时处于拒绝状态。在上面的示例中,通过从处理程序返回一个被拒绝的Promise来处理此问题。您也可以通过从处理程序中抛出一个Error来处理它。如果您不执行其中一项操作,那么当处理程序完成时,promise将处于已完成状态,并且将调用后续then
调用所提供的on complement处理程序。