最后在承诺完成之前立即调用

Ind*_*cks 10 angularjs angular-promise

一旦promise在angularjs中完成,我就会尝试执行检查.

request.then(function(res){
    $ionicLoading.hide();
    deferred.resolve(res);
  }, function(res){
    $ionicLoading.hide();
    deferred.reject(res);
  })['finally'](function(res){
      alert(res)
    }
  )
Run Code Online (Sandbox Code Playgroud)

但警报将以"未定义"的形式出现.

  1. 这是预期的还是我做错了什么?我认为只有当承诺得到解决/拒绝时才会被调用.
  2. 实现这一目标的正确方法是什么?

谢谢

Sol*_*gon 10

编辑/更新......这不是最棒的做法,而是一种简单直接的方式.当你沿着承诺链(假设你有多个)时,你需要跟踪你想要最终警告的内容,并将它存储在一个变量中.

var something = null;
request.then(function(response){
    $ionicLoading.hide();
    something = response;
  }, function(reason){
    $ionicLoading.hide();
    something = reason;
  }).finally(function(){ 
      alert(something);
  });
Run Code Online (Sandbox Code Playgroud)

一个用来证明的人:

http://plnkr.co/edit/DrqeaCAYWTQ4iWY0NPeq?p=preview


bml*_*ite 6

您正在正确地执行此操作,问题是传递给finally回调的值与返回的值successerror回调值相同.由于您没有返回任何内容,因此值未定义.

如果将return子句添加到每个回调,它应该工作:

request.then(function(res){
  $ionicLoading.hide();
  deferred.resolve(res);
  return res;
}, function(res){
  $ionicLoading.hide();
  deferred.reject(res);
  return res;
})['finally'](function(res){
    alert(res)
  }
)
Run Code Online (Sandbox Code Playgroud)

编辑

似乎Angular的finally实现还没有准备好将值传递给回调.然而,有另一种方式来产生你想要的效果,只需更换finally另一then:

request.then(function(res){
  $ionicLoading.hide();
  deferred.resolve(res);
  return res;
}, function(res){
  $ionicLoading.hide();
  deferred.reject(res);
  return res;
}).then(function(res){
    alert(res)
  }
)
Run Code Online (Sandbox Code Playgroud)

由于承诺是按顺序执行的,所以最终then将最后运行.而且,由于不必返回上任何其他的承诺successerror回调,最后then只需要一个success回调.

最终你也可以使用这样的东西:

...)['finally'](function(){ }).then(function(res){
    alert(res)
  }
)
Run Code Online (Sandbox Code Playgroud)