链式承诺尽管在链中被拒绝,但仍继续执行



>我有下面的代码,我想在发生拒绝时停止执行以进行回滚。但是,即使链中有废品,它也会继续执行。

__cacheHandheldData(userResult.handhelduuid).then((oldhandheldId) => {
olduuid = oldhandheldId;
__cacheUserdata(userResult.userdata_id) //userResult.userdata_id
}).then((x) => {
__reconciliateToNewUserData(userResult.userdata_id, handheldData.uuid)
}).then((x) => {
__linkUser(userResult._id, handheldData.userdata_id, handheldData.uuid)
}).then((x) => {
__unlinkUser(olduuid)
}).then((x) => {
__attachMergedUserdata(userResult.handhelduuid)
}).then((x) => {
__cleanHandheld(userResult.handhelduuid)
}).then((x) => {
__cleanUserdata(userResult.userdata_id)
}).then((x) => {
__cleanHandheldCache(userResult.handhelduuid)
}).then((x) => {
__cleanUserdataCache(userResult.userdata_id)
}).then((x) => {
__removeHandHeldFromRedis(userResult.handhelduuid)
}).then((x) => {
console.log('reached to destination')
var response = {};
response.errorCode = '00';
res.setHeader('Access-Control-Allow-Origin', '*');
res.send(201, response);
return next;
}).catch((err) => {
console.log('[general]', err)
});

这些__functions中的每一个都是形式

function __cacheHandheldData(oldhandhelduuid){
return new Promise((resolve, reject)=>{});}

您必须在.then()处理程序中返回承诺,如下所示:

}).then((x) => {
return __reconciliateToNewUserData(userResult.userdata_id,handheldData.uuid)
// ^^^^^^ add return here to return the promise
}).then((x) => {

只有当您从.then()处理程序中返回承诺时,它才会真正添加到链中。 没有它,它只是一个独立的承诺链,与父链完全没有联系。.then()处理程序没有神奇的力量来知道在其中执行的异步操作何时完成。 他们唯一可以知道的方法是您是否返回表示异步操作的承诺。

一旦它成为链的一部分(通过返回如上所示的承诺(,如果这些返回的承诺中的任何一个被拒绝,那么它们将中止整个链(直到下一个.catch()(。

最新更新