当前位置:网站首页>await和async
await和async
2022-06-30 18:29:00 【至尊绝伦】
1.async关键字
用于声明一个异步函数:
async是asynchronous单词的缩写,异步、非同步;
sync是synchronous单词的缩写,同步、同时;
async异步函数有很多种写法:
async function foo(){}
const foo2 = async function(){}
const foo3 = async () => {}
class Person {
async foo() {}
}异步函数的内部代码执行过程和普通的函数是一致的,默认情况下也是会被同步执行。
异步函数有返回值时,和普通函数会有区别:
- 情况一:异步函数也可以有返回值但是异步函数的返回值相当于被包裹到Promise.resolve中;
- 情况二:如果我们的异步函数的返回值是Promise,状态由Promise决定;
- 情况三:如果我们的异步函数的返回值是一个对象并且实现了thenable,那么会由对象的then方法来决定
如果我们在async中抛出了异常,那么程序它并不会像普通函数一样报错,而是会作为Promise的reject来传递;
2.await关键字
async函数另外一个特殊之处就是可以在它内部使用await关键字,而普通函数中是不可以的。
await关键字有什么特点呢?
- 通常使用await是后面会跟上一个表达式,这个表达式会返回一个Promise;
- 那么await会等到Promise的状态变成fulfilled状态,之后继续执行异步函数;
如果await后面是一个普通的值,那么会直接返回这个值;
如果await后面是一个thenable的对象,那么会根据对象的then方法调用来决定后续的值;
如果await后面的表达式,返回的Promise是reject的状态,那么会将这个reject结果直接作为函数的Promise的reject值;
边栏推荐
- NBI visual platform quick start tutorial (V) introduction to editor functions and operations
- 20200525-生物技术-四川师范大学自考生物技术(本科)考试计划.txt
- Video content production and consumption innovation
- 开发那些事儿:Linux系统中如何安装离线版本MySQL?
- 连接实验室服务器
- Personally test the size of flutter after packaging APK, quite satisfied
- Kalman滤波器--从高斯融合推导
- 法国A+ 法国VOC标签最高环保级别
- 【PHP】自研框架QPHP,qphp框架使用
- CTF流量分析常见题型(二)-USB流量
猜你喜欢

Evolution of screen display technology

Gateway服务网关

年复一年,为什么打破数据孤岛还是企业发展的首要任务

Video content production and consumption innovation

20220607跌破建议零售价,GPU市场正全面走向供过于求...

Brief introduction of Feature Engineering in machine learning

Cobbler is easy to use

Electron 入门

Unlimited cloud "vision" innovation | the 2022 Alibaba cloud live summit was officially launched

sql连续登录问题
随机推荐
企业选型作业上常犯的一个错误
Evolution of screen display technology
4个技巧告诉你,如何使用SMS促进业务销售?
CTF流量分析常见题型(二)-USB流量
10 statistical methods commonly used for "dry goods" data analysis, with key application scenarios attached
Task04:集合运算-表的加减法和join等--天池龙珠计划SQL训练营学习笔记
MQ组成部分(2022.5.16-5.22)
阿里天池SQL训练营学习笔记5
The folder is transferred between servers. The folder content is empty
【UML】UML类图
RFFE中MIPI协议
微信小程序快速入门 --项目介绍
com.alibaba.fastjson.JSONObject # toJSONString 消除循环引用
传统微服务框架如何无缝过渡到服务网格 ASM
【DesignMode】单例模式(singleton pattern)
mysql下载和安装详细教程
MQ的选择(2022.5.9-5.15)
How to seamlessly transition from traditional microservice framework to service grid ASM
3.10 haas506 2.0 development tutorial example TFT
Huaxing Securities: kitex practice under the original hybrid Cloud Architecture