Chaining Three Asynchronous Calls with jQuery Promises
You have three asynchronous HTTP calls that you need to execute in sequence, passing data from one call to the next. The provided code employs deferred objects for two functions but requires an extension for three functions.
In each case, return the jqXHR object yielded by $.ajax(). These objects are Promise-compatible, allowing chaining with .then()/.done()/.fail()/.always(). For this scenario, .then() is appropriate.
<code class="javascript">function first() { return $.ajax(...); } function second(data, textStatus, jqXHR) { return $.ajax(...); } function third(data, textStatus, jqXHR) { return $.ajax(...); }</code>
In the 'main' function, chain the functions together using .then().
<code class="javascript">function main() { first().then(second).then(third); }</code>
The arguments data, textStatus, and jqXHR originate from the $.ajax() invocation in the preceding function. In other words, first() supplies second(), and second() supplies third().
(For illustration, use $.when('foo') to produce a fulfilled promise in place of $.ajax(...)).
The above is the detailed content of How to Chain Three Asynchronous Calls Sequentially with jQuery Promises?. For more information, please follow other related articles on the PHP Chinese website!