1 //returns the calculated result of Input*input after 0.5 seconds:2 functionMultiply (input) {3 return NewPromise (function(Resolve, reject) {4Log (' calculating ' + input + ' x ' + input + ' ... '));5SetTimeout (Resolve, $, input *input);6 });7 }8 9 //returns the calculated result of Input+input after 0.5 seconds:Ten functionAdd (Input) { One return NewPromise (function(Resolve, reject) { ALog (' calculating ' + input + ' + ' + ' + input + ' ... ')); -SetTimeout (Resolve, +, input +input); - }); the } - - varp =NewPromise (function(Resolve, reject) { -Log (' Start new Promise ... '); +Resolve (123); - }); + A p.then (multiply) at . Then (add) - . Then (multiply) - . Then (add) -. Then (function(Result) { -Log (' Got value: ' +result); -});
Operation Result:
Start new Promise ...
Calculating 123 x 123 ...
Calculating 15129 + 15129 ...
Calculating 30258 x 30258 ...
Calculating 915546564 + 915546564 ...
Got value:1831093128
Code parsing: Resolve is a successful execution
Reject is execution failure
Prototype.then () Deferred processing
Prototype.catch () anomaly capture
Using SetTimeout to simulate asynchronous
Each step of the above code executes the function's settimeout (resolve, x, input * input), the first parameter label which is the function of the successful state execution, the second parameter is delayed 500 milliseconds, and the third argument is passed to the value of the next function.
1' Use strict ';2 3 //The AJAX function returns the Promise object:4 functionAjax (method, URL, data) {5 varRequest =NewXMLHttpRequest ();6 return NewPromise (function(Resolve, reject) {7Request.onreadystatechange =function () {8 if(Request.readystate = = 4) {9 if(Request.status = = 200) {Ten Resolve (Request.responsetext); One}Else { A reject (request.status); - } - } the }; - Request.open (method, url); - request.send (data); - }); + } - + varLog = document.getElementById (' Test-promise-ajax-result '); A varp = Ajax (' GET ', '/api/categories '); atP.then (function(text) {//If Ajax succeeds, get response content - - Console.log (text); -},function(status) {//If Ajax fails, get the response code -Console.log (' ERROR: ' +status); -});
The above code is the Ajax asynchronous execution function converted to a Promise object.
JS in the Promise use