最近一年的新内容

JS :

1. async ......一个promise的语法糖(内部还是用promise封装),比promise更简单

 一、Promise函数

 1  var f1 = function () {
 2             return new Promise(
 3                 res => {
 4                     //必须要告诉外界 我执行完了。
 5                     console.log("执行一些函数");
 6                     setInterval(() => {
 7                         res("你好")
 8                     }, 1000)
 9                 }
10             )
11         };
12 
13         (async function () {
14             //await是表示这行代码是一个异步操作
15             let res = await f1();
16             console.log("第一次:", res);
17             res = await f1();
18             console.log("第二次:", res);
19 
20         })()   

二 、本身是async函数

 1 var o1={
 2         say:async ()=>{
 3             console.log('say方法:');
 4 
 5             const res = await q();
 6 
 7             console.log(res);
 8         },
 9         run:async function(){
10             console.log('run方法');
11 
12             const res = await q();
13 
14             console.log(res);
15         }
16     }
17 
18     //需求,先执行完毕say,再执行run
19     var fn=async function(){
20         await o1.say();
21 
22         await o1.run();
23     }
24     fn();

 要想使用asycn函数,必须是promise函数 或者本身就是async函数

 

注意:  async标记的函数只能在函数内部执行,不能在全局执行,所以 至少要自执行函数包起来。

 三、错误处理

 1 function q(){
 2         return new Promise((resolve,reject)=>{
 3             setTimeout(()=>{
 4                 resolve("正确");
 5             },100)
 6         })
 7     }
 8 
 9     (async function(){
10         try{
11             let res = await q();
12             console.log(res);
13         }catch(err){
14             console.log(err);
15         }
16     })()
原文地址:https://www.cnblogs.com/it-Ren/p/10647792.html