Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain multiple promises in Angularjs

I have the following structure and need to simplify it,

Resuable service1 to interact with IndexedDB

function isDbExist (){
// do something , it return either reject or resolve
}

function createDB (){
// do something , it return either reject or resolve
}

function getData (){
    // do something , it return either reject or resolve
}

In another service2 I'm injecting this service1 and using the functions as such

function1 (){
service1.isDbExist.then(function(data){
   service1.createDB.then(function(data){
      service1.getData.then(function(data){
        referred.resolve(data);
      },function(error){
       deferred.reject(error)
      })
   },function(error){
    deferred.reject(error);
   })
},function(error){
   deferred.reject(error);
})
}

The problem here is the readability of the code is not good, its not easy to debug as which reject function is for which promise. Is their some good way of doing this ? I have read about $q.all but don't this its applicable in this situation.

like image 582
Gaurav_soni Avatar asked Dec 19 '22 02:12

Gaurav_soni


1 Answers

Exactly, the beauty of promises is that you can chain them as opposed to nesting them like callbacks. You can return another promise when dealing with the previous like so:

isDbExists().then(function(db) {
  // do something
  return createDb();
}).then(function(db) {
  // do something with with the resolved db..
  return getData();
}).then(function(data) {
  // Do something with data
}).catch(function(error) {
  // Uh oh, something went wrong. Deal with error
});

Finally, you deal with the error that may have occurred.

like image 185
juco Avatar answered Dec 24 '22 00:12

juco