Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

jquery - JavaScript : Ordering AJAX calls

I have 3 ajax call for particular functionality. 3rd call is dependent of first 2 calls i.e. for the 3 rd call first 2 calls has to be finished. But first 2 AJAX calls are independent. So I want them to be async and execute parallely.

How to structure these calls now? I tried to put them in nested success block of respective calls, but it that case first 2 calls are also not independent.

Kindly suggest with some sudo code, if possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use promises and $.when:

$.when(ajaxCall1(), ajaxCall2()).then(ajaxCall3);

where ajaxCallX is something like

function ajaxCall1() {
    return $.ajax(...);
}

This basically means "after both, the promise of ajaxCall1 and the promise of ajaxCall2 are resolved, execute the function ajaxCall3".

This works because the object returned by $.ajax (and similar methods) implements the promise interface. More information can also be found in the $.ajax documentation.


The responses of each Ajax call are passed to the then callback as arguments. You can acess them as

$.when(ajaxCall1(), ajaxCall2()).then(function(a1, a2) {
    // a1[0] is the response of the first call
    // a2[0] is the response of the second call
    ajaxCall3(a1[0], a2[0]);
});

Have a look at the $.when documentation for another example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...