promise - 反复进行回调函数.
1 <!DOCTYPE html>
2 <html lang="en">
3
4 <head>
5 <meta charset="UTF-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <meta http-equiv="X-UA-Compatible" content="ie=edge">
8 <title>Promise</title>
9 </head>
10
11 <body>
12 <script>
13 // ES5
14 function async(a, b, c) {
15 setTimeout(function() {
16 c(a + b);
17 }, 200);
18 }
19
20 // 反复回调 ... 再次
21 async(1, 2, function(result) {
22 console.log(result);
23 if (result > 2) {
24 async(2, result, function(result) {
25 console.log(result);
26 if (result > 4) {
27 async(2, result, function(result) {
28 console.log('result');
29 });
30 }
31 });
32 }
33
34 });
35 console.log(2);
36
37
38 // ####################################################################################################
39
40
41 // ES6 - promise
42 function asyncPromise(a, b) {
43 return new Promise(function(resolve, reject) {
44 setTimeout(function() {
45 // 如果值不为number对象
46 if (typeof a !== 'number' || typeof b !== 'number') {
47 reject(new Error('no number'));
48 }
49 resolve(a + b);
50 }, 200);
51 });
52 }
53 // 错误捕获 - 一旦开始捕获了,catch就不会再重新捕获
54 asyncPromise('a', 2)
55 .then(function(result) {
56 if (result > 2) {
57 return asyncPromise(result, 2);
58 }
59 }, function(err) {
60 console.log('one no number!');
61 })
62 .then(function(result) {
63 if (result > 4) {
64 console.log('result');
65 }
66 }).catch(function(err) {
67 console.log(err);
68 });
69 </script>
70 </body>
71
72 </html>