0

I have the following code:

var arrOutfit = []; // will be filled
...
$.when(

  $.each(arrOutfit, function(key, sAdd) {

    $.post('/checkout/addArticle', 'sAdd=' + sAdd + '&sQuantity = 1');

  });

).then() {

  // something

}

But this does not work. I figured that the array loop is invalid. As you can see I have mutliple ajax calls and I want to have just one callback, so I know, when all requests has been done. How can I achieve this?

Any ideas will be appreciated.

Best regards

1 Answer 1

2

Your usage of $.when is not quite correct. Try this:

var arrOutfit = [], // will be filled
    promises = [];

// ...

$.each(arrOutfit, function(key, sAdd) {
    promises.push($.post('/checkout/addArticle', 'sAdd=' + sAdd + '&sQuantity = 1'));
});

$.when.apply($, promises).then(function(schemas) {
    // something...
});

Note that the each is used to populate an array with promises which are then provided to the when which will execute once they are all complete.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, thank you very much. This works. But I really don't understand why. Do you have any references or keywords for me to get a better understanding?
@user3180943 - $.when() takes one or more promises as arguments. You can't just pass it some function and expect it to know when that code is done. It only knows when promises that you pass it are done. Rory's answer builds an array of promises from the return value of $.post() ($.post() returns a promise) and then it uses .apply() to simulate calling $.when(p1, p2, p3, p4) using the array of promises.
@jfriend00 Thank you. I now understand what is going an. I still have a question though: Am I correctly with the assumption, that the $.post(...) gets executed in the $.each loop? If I comment out the $.when(...) part, I'll see those requests in my console. So between $.each and $.when, there is a timeframe, even it is little, where the $.post() could finish without noticing by $.when()?
@user3180943 - no that wouldn't happen. Javascript is single threaded. The $.post() calls cannot execute their success handlers or promise fullfillment until after your $.each() loop finishes and the rest of that thread of execution finishes. If the actual HTTP POST finishes sooner, the response will be queued up by the JS runtime until the current thread of execution is finished and then, and only then, will the completion handlers be called. So, $.when() can not and will not miss the completion of your $.post() calls. This is by design in javascript to make things simpler.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.