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.