Gaurav_soni
Gaurav_soni

Reputation: 6114

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.

Upvotes: 4

Views: 4520

Answers (3)

dfsq
dfsq

Reputation: 193301

You can chain multiple promises like this:

service1.isDbExist()
    .then(service1.createDB)
    .then(service1.getData)
    .then(function() {
        // DB exists, created and data loaded
    })
    .catch(function(err) {
        console.log('Handle error', err); // isDbExist, createDB or getData rejected
    });

Check interactive demo to see how success and error data is passed to the next promise in chain and how you have full control over process on each step:

Demo: http://plnkr.co/edit/PM06e8NGJvHKmoJ9C2Lf?p=info

Upvotes: 5

Emil Ingerslev
Emil Ingerslev

Reputation: 4785

One of the really great things about promises is that they can be chained like this:

function1 (){
  return service1.isDbExist.then(function(exists){
    if(!exists) return service1.createDB()
  })
  .then(function() {
    return service1.getData('some', 'args')
  });
}

Remember that the .then will receive the result of the previous function, like the exists would be a boolean. function1 will also return a promise and this promise will return the resolved/rejected promise from service1.getData.

Upvotes: 0

juco
juco

Reputation: 6342

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.

Upvotes: 6

Related Questions