es6 - Promise
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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现