Home  >  Article  >  Web Front-end  >  Promise processing instance that completes multiple interdependent asynchronous requests

Promise processing instance that completes multiple interdependent asynchronous requests

巴扎黑
巴扎黑Original
2018-05-24 13:45:513395browse

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(){
      })
    })

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!

Statement:
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