4

I'm using deferred as I need to execute several processes asynchronously.

To be clearer, here is the signification of my treatments :

  • Treatment1 : call of an ajax service providing user rights
  • Treatment2 : call of an ajax service providing links and labels.

I need to call these 2 services at the same time and then get the unified response of both services in order to display links depending on rights (my real problem is with a 3rd ajax service but let's talk about with only 2 to simplify).

First, I declare the deferred as global var :

var treatment1 = $.Deferred();
var treatment2 = $.Deferred();

Then, when I need to do the job, I call the resolve method with needed data for using it in the global unique treatment:

  • when my 1st ajax service responds : treatment1.resolve(responseData1)
  • when my 2nd ajax service responds : treatment2.resolve(responseData2)

When the treatment1 & 2 are finished, the done event is fired :

$.when(treatment1, treatment2).done(function(responseData1,responseData2) {
    DoGlobalTreatmentWithAllResponseData(responseData1,responseData2)
}

My problem is that deferred works only once.

As my website is realized in ajax mainly, I need to fire the event multiple times.

The user can click a button to search for users. Then a list of users is displayed and the ajax services are all called asynchronously. This operation can be repeated infinitely.

I just need a way to reuse the principle of deferred but multiple times. I know that this problem has already been discussed and everyone says deferred can't work this way.

But, is it really not possible to reset the deferred state or reset the promises (even by implementing a custom solution, using AOP or something else)?

If it's impossible, what solution could I use? I don't want to fire treatments one after another but I really want to do a global treatment after all the treatments are finished (that is to say, after the last treatment in activity is finished) and I want to use the responseData of each services.

Here is my sample code that I would like to customize : http://jsfiddle.net/PLce6/14/

I hope to be clear as English is not my native language.

Thank you in advance for your help.

3 Answers 3

3

Deferreds can be resolved/rejected only once... However, I think the issue is how you're structuring your code...

As long as you're initializing your deferred each time, there isn't any problem in doing this... I think the issue is this:

First, i declare the deferred as global var:

var treatment1 =$.Deferred(); 
var treatment2 = $.Deferred();

Instead, can you try doing this in a function that's invoked in the button click

The user can clic a button to search for users

so have a function like so:

function onClick() {
    var treatment1 =$.ajax({url: '/call1'}); 
    var treatment2 = $.ajax({url: '/call2'});
    $.when(treatment1, treatment2).done(function(obj1, obj2) {
            // do whatever else you need
    });
}

Now from the rest of your post, looks like you're trying to reuse the deferreds - but in that case, your original solution should not have a problem with keeping deffereds as global since your done will be called with whatever data they were resolved with.

Can you post some more of your code to help explain what you're trying to do.

Updated from my own comment below for elaboration

based on op's fiddle, he wants to be able to trigger dependent action multiple times. Solution is to have the dependent action create new deferreds and hook up a $.when to itself. See updated fiddle at http://jsfiddle.net/PLce6/15/

// global
var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();

// here's the reset 
function resetDeferreds() {
d1 = $.Deferred();
d2 = $.Deferred();
d3 = $.Deferred();
$.when(d1, d2, d3).done(
    function (responseData1, responseData2, responseData3) {
       DoGlobalTreatmentWithAllResponseData(responseData1, responseData2, responseData3);
    resetDeferreds();
});

// the onclick handlers
function do3() {
d3.resolve('do3 ');
return d3;
}

// the top level $.when
$.when(d1, d2, d3).done(function (responseData1, responseData2, responseData3) {
    DoGlobalTreatmentWithAllResponseData(responseData1, responseData2, responseData3);
    resetDeferreds();
});
4
  • the way my code is structured, i cannot get the result directly from my ajax service as there is some tratment after the ajax call. Please see my sample code updaded at the end of my thread. Thx
    – seblurtz
    Nov 14, 2013 at 17:16
  • The issue is that each click event triggers it's own deferred behavior and cues a dependent response. That dependent response requires a set of deferred calls to have completed. See his example on jsfiddle. and my edit, linked above in my "answer" comment.
    – mangr3n
    Nov 14, 2013 at 18:11
  • @seblurtz: url to fiddle jsfiddle.net/PLce6/15 it does what you wanted... Basically, once all the dependent action is taken, create a new set of deferreds and set up a new $.when on them to take the same action.
    – Raghu
    Nov 14, 2013 at 18:30
  • 1
    Yes it's it, the solution is just so simple. I need to not just reinitialise the deferred but also the mapping on the event by redefining the $.when().done() functions. Great Thanks for your help. I updated my jsfiddle here in last working version : jsfiddle.net/PLce6/19
    – seblurtz
    Nov 15, 2013 at 8:19
1

Perhaps you code is not well designed?

I do not see how that would be an issue. The asynchronous process should be responsible for creating a new Deferred object everytime.

function doSomething() {
    var d = $.Deferred();

    setTimeout(function () {
        d.resolve();
    }, 1000);

    return d;
}

function doSomethingElse() {
    var d = $.Deferred();

    setTimeout(function () {
        d.resolve();
    }, 1000);

    return d;
}

Then you can always do the following:

$.when(doSomething(), doSomethingElse()).done(function () {
    console.log('done');
});

There's always a solution:

If you absolutely need to be able to call resolve multiple times on the same Deferred, then you should wrap the Deferred into another object, let's say DeferredWrapper, which would expose the same API as a Deferred but would delegate all method calls to the it's encapsulated Deferred.

In addition of delegating the function calls, the DeferredWrapper would have to keep track of all listening operations (e.g. done, always, fail...) that were made on the object. The DeferredWrapper could store all actions as [functionName, arguments] tuples in an internal this._actions property.

Finally, you would need to provide a special implementation for state changing operations (e.g. reject, resolve, resolveWith...etc) that would look like:

  1. Let d be the internal Deferred referenced by this._deferred.

  2. Let fn be the function name of the function being called.

  3. If d.state() is not pending:

    3.1 Do d = this._deferred = [[native jQuery Deferred]]

    3.2 Apply all actions on d.

  4. Return the result of d[fn].apply(d, arguments)

Note: You would also need to implement a custom promise implementation and make sure it behaves correctly. You can probably use a similar approach like the one described.

1
  • But using this way, you are just executing the method doSomething() & doSomethingElse() direclty no ? See my sample code on jsfiddle please.
    – seblurtz
    Nov 14, 2013 at 17:32
0

I'm going to suggest a small change. One element you weren't clear on is whether or not the treatment1 and treatment2 results are different each time. If they are then do what @raghu and @juan-garcia

function onClick() {
    var treatment1 =$.ajax({url: '/call1'}); 
    var treatment2 = $.ajax({url: '/call2'});
    $.when(treatment1, treatment2).done(function(obj1, obj2) {
            // do whatever else you need
    });
}

If they don't change then do this :

var treatment1 =$.ajax({url: '/call1'}); 
var treatment2 = $.ajax({url: '/call2'});

function onClick() {
    $.when(treatment1, treatment2).done(function(obj1, obj2) {
            // do whatever else you need
    });
}

Or some variation of that. Because once they are complete, your callback function will always execute right away. It's still asynchronous, but it doesn't need to wait since everything is ready to go. This serves both use cases. This is a very common pattern for data that may take a few seconds to load before it's functionally useful when drawing a new component in the page. It's a lazy-load mechanism that's very useful. Once it's in though everything looks as if it's responding instantaneously.

I reworked the javascript in your example on JSFiddle to show just the basics I think you needed to see. That is here. Given your example, I think the mistake is in believing that resolve must be called multiple times to trigger a behavior. Invoking the done behavior cues a one time behavior and each invocation of done loads a new behavior into the queue. Resolve is called one time. $.when().done() you call as many times as you have behaviors dependent on the specific when() condition.

6
  • the way my code is structured, i cannot get the result directly from my ajax service as there is some tratment after the ajax call. Please see my sample code updaded at the end of my thread. Thx
    – seblurtz
    Nov 14, 2013 at 17:33
  • jsfiddle.net/MwNN9 I forked your code. @seblurtz. There's a misconception, IMO, of how this works. Once resolved cannot re-resolve. You simply have to push $.when(x,y,z).done(doSomethingWithResolvedData); behind the event that you want to trigger that behavior. It only waits if any of the deferred are not resolved. Resolve says I'm ready. Each invocation of when is a single follow up behavior. Add a when().done() behavior to each click handler.
    – mangr3n
    Nov 14, 2013 at 18:02
  • @seblurtz Glad I could help. Maybe you could accept the answer?
    – mangr3n
    Nov 15, 2013 at 12:24
  • Sorry i chose Raghu's answer because he wrote the entire code solution.
    – seblurtz
    Nov 15, 2013 at 13:18
  • np, I didn't see that when I responded. BTW, don't recreate the deferred's unless the data changes.
    – mangr3n
    Nov 15, 2013 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.