尽管链条遭到拒绝,但链式承诺仍在继续执行

时间:2017-07-09 19:11:37

标签: javascript ecmascript-6 promise

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

__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)
});

这些__功能中的每一个都是

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

1 个答案:

答案 0 :(得分:2)

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

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

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

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