Home > Web Front-end > JS Tutorial > How to Chain Three Asynchronous Calls Sequentially with jQuery Promises?

How to Chain Three Asynchronous Calls Sequentially with jQuery Promises?

Linda Hamilton
Release: 2024-10-29 08:20:30
Original
790 people have browsed it

How to Chain Three Asynchronous Calls Sequentially with jQuery Promises?

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>
Copy after login

In the 'main' function, chain the functions together using .then().

<code class="javascript">function main() {
    first().then(second).then(third);
}</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template