nespapu
nespapu

Reputation: 812

Sync methods inside angular chaining promises

I am coding a method which is a composition of multiple promises:

function myMethod(){
    var deferred = $q.defer();
    asyncMethod1(data1).then(function(){
        return asyncMethod2(data2);
    }).then(function(){
        return asyncMethod3(data3)
    }).then(function(){
        deferred.resolve(1);
    }).catch(function(error){
        //TODO
    });

    return deferred.promise;

The asyncMethods do work as the following:

function asyncMethodn(data){
    var deferred = $q.defer();
    if(data.lenght == 0){
       //Nothing to do. Skip method.
       //deferred.resolve()?
       //return;?
    }

    anotherAsyncMethod(data).then(function(){
        deferred.resolve();
    }).catch(function(error){
        deferred.reject();
    });

   return deferred.promise;
}

I am trying to figure out how to deal with the case when the data lenght in the asyncMethod is 0. In this case the method would be sync instead of async. What happens with the chain of promises? How you guys would handle this?

Thanks in advance.

Regards.

Upvotes: 0

Views: 272

Answers (2)

marco.broccio
marco.broccio

Reputation: 63

function asyncMethodn(data){
    var deferred = $q.defer();
    if(data.lenght == 0){
       deferred.resolve();
       return;
    }

    anotherAsyncMethod(data).then(function(){
        deferred.resolve();
    }).catch(function(error){
        deferred.reject();
    });

   return deferred.promise;
}

Upvotes: 0

Chandermani
Chandermani

Reputation: 42669

For sake of consistency always return a promise, as you are doing already in asyncMethodn.

The if condition should just return deferred.resolve() and promise chaining in the calling function would work seamlessly. In such a case (data.length=0) the promise would be resolved immediately.

You can also use the resolved value of asyncMethodn to decided if further call chaining is required.

Upvotes: 1

Related Questions