Home > Web Front-end > JS Tutorial > body text

Promise processing instance that completes multiple interdependent asynchronous requests

巴扎黑
Release: 2018-05-24 13:45:51
Original
3492 people have browsed it

The following editor will bring you an article on promise processing of multiple interdependent asynchronous requests (explanation with examples). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look

In projects, we often encounter multiple asynchronous requests that depend on each other. If there are three ajax requests a, b, and c, b needs to rely on the data returned by a, and c needs the data returned by a and b requests. It is naturally not advisable to use nested requests. It makes the code difficult to maintain and there are many requests. Many questions will arise.

Promise is to solve the problem of multiple asynchronous requests. Promise is an object provided by ES6, used to deliver messages for asynchronous operations.

Promise has three states: Pending (in progress), Resolved (completed, also known as Fulfilled) and Rejected (failed).

Upload the code directly. There are requests for a and b, and b depends on the request data of a. As follows:

function a(){
      return new Promise(function(res,rej){
        $.ajax({
          url:"a",
          type: "GET",
          async:true,
          dataType:"json",
          success:function(data){
            console.log(data,"a");
            res(data);
          }
        })
      });
    }
    function b(data){
      console.log(data,"data");
      return new Promise(function(res,rej){
        $.ajax({
            url:"b",
            type: "POST",
            async:true,
            data:JSON.stringify(data),
            dataType:"json",
            success:function(data){
              console.log(data,"b");
              res();
            }
          })
      });
    }
    $("#btn").click(function(){
      a().then(function (data){
        b(data);
      }).then(function(){
      })
    })
Copy after login

I found one on the Internet for the interface url. You can see the running results:

The above is the detailed content of Promise processing instance that completes multiple interdependent asynchronous requests. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template