Finally gets called immediately before promise gets fulfilled

Indyarocks picture Indyarocks · Sep 4, 2014 · Viewed 19.8k times · Source

I'm trying to execute a check once promise gets fulfilled in angularjs.

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

But the alert is coming as 'undefined'.

  1. Is that expected or I'm doing anything wrong? I thought it'll get called only when promise gets resolved/rejected.
  2. What is the right way to achieve this?

Thanks

Answer

SoluableNonagon picture SoluableNonagon · Sep 4, 2014

Edit/Update ... This is not the most awesome way of doing, but a simple and straightforward way. You need to keep track of what you want to to finally alert as you go down the chain of promises (assuming you have multiple), and just store it in a variable.

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

A plunker to demonstrate:

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