js中的promise使用


 1 // 0.5秒后返回input*input的計算結果:
 2 function multiply(input) {
 3     return new Promise(function (resolve, reject) {
 4         log('calculating ' + input + ' x ' + input + '...');
 5         setTimeout(resolve, 500, input * input);
 6     });
 7 }
 8 
 9 // 0.5秒后返回input+input的計算結果:
10 function add(input) {
11     return new Promise(function (resolve, reject) {
12         log('calculating ' + input + ' + ' + input + '...');
13         setTimeout(resolve, 500, input + input);
14     });
15 }
16 
17 var p = new Promise(function (resolve, reject) {
18     log('start new Promise...');
19     resolve(123);
20 });
21 
22 p.then(multiply)
23  .then(add)
24  .then(multiply)
25  .then(add)
26  .then(function (result) {
27     log('Got value: ' + result);
28 });

運行結果: 

start new Promise...

calculating 123 x 123...

calculating 15129 + 15129...

calculating 30258 x 30258...

calculating 915546564 + 915546564...

Got value: 1831093128

 

代碼的解析: resolve 是執行成功

      reject 是執行失敗

      prototype.then()  遞延處理

      prototype.catch()  異常捕捉

      使用setTimeout 模擬異步

以上代碼每一步then都會執行函數中的setTimeout(resolve, 500, input * input), 第一個參數標簽這是成功狀態執行的函數, 第二參數延時500毫秒,第三參數傳遞給下一個函數的值。

 1 'use strict';
 2 
 3 // ajax函數將返回Promise對象:
 4 function ajax(method, url, data) {
 5     var request = new XMLHttpRequest();
 6     return new Promise(function (resolve, reject) {
 7         request.onreadystatechange = function () {
 8             if (request.readyState === 4) {
 9                 if (request.status === 200) {
10                     resolve(request.responseText);
11                 } else {
12                     reject(request.status);
13                 }
14             }
15         };
16         request.open(method, url);
17         request.send(data);
18     });
19 }
20 
21 var log = document.getElementById('test-promise-ajax-result');
22 var p = ajax('GET', '/api/categories');
23 p.then(function (text) { // 如果AJAX成功,獲得響應內容
24     25     console.log(text);
26 },function (status) { // 如果AJAX失敗,獲得響應代碼
27     console.log('ERROR: ' + status);
28 });

以上代碼吧AJAX異步執行函數轉換為promise對象。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM