0

I have 2 functions.

function f1() {
    $.ajax(..., success: function(response) {
        // some code executed whenever request is completed.
    }
}

function f2() {
    // my code
}

I need to call these functions one after another.

f1() // waiting until ajax request in the function is complete.
f2()

I tried $.when().then(), however it didn't seem to work.

3 Answers 3

2

The $.ajax call returns an instance of $.Deferred which is used to track the progress of the call - that is what you need to return from your f1 function. You can then use .then(), .done() etc.

Edit in response to comments

If you want to invoke a callback within f1 as well as externally you can return the result of the .pipe method.

function f1() {
    return $.ajax(/*...*/).pipe(function() {
        //local 'done' handler
    });
}

function f2(resultFromF1Handler) {
    //...
}

f1().done(f2);
Sign up to request clarification or add additional context in comments.

2 Comments

That work's, however, f2 is still executed a little bit too early. I need to call f2 after ajax request and its callback in f1 is executed.
@Hvandracas see my edit - updated example with callback in f1
1
function f1(onsuccess) 
{
    $.ajax(
    { 
        success: function(r) 
        { 
            // some code
            onsuccess(r);
        }
    });
}

function f2() 
{
    // my code
}

f1(f2);

3 Comments

This works, but is not as flexible as using $.Deferred: what if you want to attach 2 'success' handlers? Or a 'fail' handler?
@Steve, true but workable... function success(){ f2(); f3();} f1(success, fail);
+1 If you don't already know how to use deferreds, this is the most straightforward way to call f2() from f1() without f1 knowing any specifics of f2. All it's doing is designing f1() to support calling an arbitrary function after its ajax call succeeds.
0

I suggest calling f2() inside the anonymous function that is executed as f1()'s success.

Is there a problem with doing that?

1 Comment

But that would mean that f1 needs to be aware of f2. By using the $.Deferred, these two functions could be in separate files or separate libraries and still work as the OP desires

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.