Promise processes multiple interdependent asynchronous requests (for example ).

Source: Internet
Author: User

Promise processes multiple interdependent asynchronous requests (for example ).

In projects, multiple interdependent asynchronous requests are often encountered. If there are three ajax requests, a, B, and c, B must depend on the data returned by a, and c needs the data returned by requests a and B. If the request is nested, it is naturally not desirable. As a result, the code is difficult to maintain and many requests are requested. There will be many problems.

Promise solves multiple asynchronous requests.Promise is an object provided by es6. it is used to transmit messages of asynchronous operations.

Promise has three statuses:Pending (in progress), Resolved (completed, also called Fulfilled), and Rejected (failed ).

Directly add the code. Requests a, B, and B depend on request data of. 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(){      })    })

An interface url is found online. You can view the running result:

The above promise process multiple mutually dependent asynchronous requests (for example) is all the content shared by the small editor. I hope you can provide a reference and support for the customer's house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.