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对象。

猜你喜欢

转载自www.cnblogs.com/jiayiming/p/9099655.html