This article mainly share with you the use of Ajax and promise method, the need to rely on the completion of the AJAX request can be used promise guarantee the execution order
A second request is sent after the first request is returned correctly. Hope to help everyone.
/* define an AJAX request using promise, where the request URL in the jquery parameter is required */const ajaxpromise= param + = { return new Promise ((Resovle, reject) = { $.ajax ({ "type":p Aram.type | | "Get", "async":p Aram.async | | true, "url":p aram.url, "data":p Aram.data | | "", "Success": res = = { Resovle (res); }, "error": Err = { reject (err); } ) })} /* The first request */let Step1 = () = { Ajaxpromise ({ "url": "", }). Then (res = { Console.log (" The first request correctly returns ==> "+res"); Step2 (res); }). catch (err + = { Console.log ("First request Failed")} )} /* Second request */let Step2 = (res) + { ajaxpromise ({ "type": "Get", "url": "", "data": {"name": RES} ). Then (res = { Console.log ("Second request correctly returns ==>" +res)) . catch (err + = { Console.log ("Second request failed ==>" +err) })} Step1 ();
Native JS Write Ajaxpromise object
Const Ajaxpromise = param = { return new Promise ((Resovle, reject) = = { var xhr = new XMLHttpRequest (); xhr.open (Param.type | | "Get", Param.url, true); Xhr.send (Param.data | | null); Xhr.onreadystatechange = () = { var done = 4;//ReadyState 4 indicates that a request has been sent to the server var OK = $;//status 200 means that the server returns if (xhr.readystate = = = done) { if (xhr.status = = = OK) { Resovle (Json.parse (Xhr.responsetext)); } else{ Reject (Json.parse (Xhr.responsetext);}}} )}
Some points about the use of promise:
How to use: first create a Promise object new Promise (), determine the execution success or failure based on business requirements, successfully call Resovle (), and fail to invoke reject ().
The then (onfulfilled,onrejected) of the Promise object has two parameters, executed successfully onfulfilled, failed execution onrejectd
P.then (function (value) { //Fulfillment succeeded }, function (reason) { //rejection failed});//But usually catch () is used to catch the failure, The previous segment code is usually written as: P.then (function (value) { //Fulfillment success}). catch (function (reason) { //rejection failed})
Then () of the Promise object returns a new Promise Object
Related recommendations:
Small program promise simplifies callback instance sharing
How the promise of jquery is used correctly
Simple usage of Promise objects