最近一年的新内容

本文深入讲解了JavaScript中async函数和Promise的基本概念与使用方法。包括如何定义和使用Promise,async函数的基本语法及其与Promise的区别,以及如何处理async函数中的错误。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值