Itai Sagi
Itai Sagi

Reputation: 5615

jquery $.when $.then issue

I try to use $.when with ajax calls, where on of the calls won't always be called, how can I achieve this. I've been trying to hack around it

var renderThis;
$.when($.post("/blabla", function(data){
            renderThis = data;
        }),
        function(){
            if(another){
                return $.post("/blabla");
            }
            else{
                return true;
            }
        })
        .then(function(){
            render(renderThis)
        });

but what I see is that the $.then() isn't called in a deferred manner but is called instantly.

any ideas?

Upvotes: 2

Views: 88

Answers (2)

Robert Koritnik
Robert Koritnik

Reputation: 105091

.when needs function results instead of function references. Your second parameter to .when is function reference. Try using an immediately executing function instead:

$.when(
    $.post("/blabla"),
    (function() {
        if(another){
            return $.post("/blabla");
        }
        else{
            return true;
        }
    })())
.then(
    function(data1, data2){
        render(data1);
    });

As you can see I've also consolidated first success function to be process on when instead providing it inline with .post call.

Upvotes: 5

Arun P Johny
Arun P Johny

Reputation: 388446

Try

var requests = [$.post("/blabla")];
if (another) {
    requests.push($.post("/blabla"))
}
$.when.apply($, requests).then(function (data1) {
    render(data1[0])
});

Upvotes: 2

Related Questions