0

i am trying to sync three functions which have AJAX calls in them.

main(){
compileTemplate();
}

compileTemplate(){
func1();
func2();
func3();
}

each func has structure like :

func(){
$.when($.get(url)).then(func(d)
{//do something});

Each func() is completing on its own. i need when func1 completes then func2 should start.

checked

 $.when(func1()).then(func2()); 

but its not working. please do anyone has any idea.

1
  • you want to use function reference, not returned value (if any): .then(func2); FYI, chaining .then() has not expected behaviour in jq<1.8 Commented Nov 26, 2013 at 12:17

2 Answers 2

4

Make sure that the return value of func1, func2 and func3 are promises:

function func1() {
    var d = new $.Deffered();
    setTimeout(function () {
        d.resolve();
    }, 1000);
    return d.promise();
}
function func2() {
    return $.ajax(/* .. */);
}
function func3() {
    return /* etc */
}

Then you can:

$.when(func1()).then(func2).then(func3); // notice the () or lack thereof

Or:

$.when(func1()).then(function () {
    return func2();
}).then(function () {
    return func3();
});

If you don't know whether func1, func2 and func3 will always return a promise this will still work, but you can not wait for it.


If you do:

$.when(func1()).then(func2()).then(func3());

func1, func2 add func3 will be called immediately, rather than serially. This is equvalent to:

var a = func1();
var b = func2();
var c = func3();
$.when(a).then(b).then(c);
//or
$.when(a, b, c);
Sign up to request clarification or add additional context in comments.

1 Comment

That makes more sense.
0
function func1() {
  if (ajaxObject.readyState == 4 && ajaxObject.status == 200) {
  ajaxObject.onreadystatechange = func2;
  ajaxObject.send();
  }
}

function func2() {
  if (ajaxObject.readyState == 4 && ajaxObject.status == 200) {
  ajaxObject.onreadystatechange = func3;
  ajaxObject.send();
}

function func3() {
}

1 Comment

This creates a coupling between func1, func2 and func3 that is not present in OPs sample.

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.