2

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?

2 Answers 2

5

.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.

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

Comments

2

Try

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

Comments

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.