Skip to content Skip to sidebar Skip to footer

Is There A Way To Trigger Call A Method In Another Module That "might" Exist?

I know this is a base question... but I'll try to explain. I've been using a Deferred, but someone pointed out that I'm using it as an anti-pattern. Basically, I can use the deferr

Solution 1:

A promise is an abstraction over a single, one time calculation of a value. A promise starts pending, and then can transition to either fulfilled or rejected state. Once a promise resolved (transitioned) it can never change its state again.

Deferreds are used in exactly one - when you want to construct a promise from something that's not a promise*.

In jQuery $.ajax already returns a promise to begin with.

Z.a = function(){ // this method now returns a promisereturn $.ajax({...});
};

If we want to chain it, we can use .then :

Z.a().then(function(){
    // here a() is done.
});

You can also use a caching pattern, using $.when (Promise.resolve in most promise libraries):

Z._a = null;
Z.a = function(){
    if(z._a){ // already have the value cached:return $.when(z._a); // promise over the value
    }
    return $.ajax({...}).then(function(res){
        Z._a = res;
        return res; // chain
    });

};

Z.b = function(){
    return Z.a().then(function(aValue){
        // do something with value, your return value here is the resolution// value of the a method call.
    });
}

Now, if you want to wait for multiple calls, you can use $.when with multiple promises and get their results.

Post a Comment for "Is There A Way To Trigger Call A Method In Another Module That "might" Exist?"