当前位置:网站首页>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值;
边栏推荐
- Brief introduction of Feature Engineering in machine learning
- Redis入门到精通01
- 详解kubernetes备份恢复利器 Velero | 深入了解Carina系列第三期
- 拓維信息使用 Rainbond 的雲原生落地實踐
- 拓维信息使用 Rainbond 的云原生落地实践
- Nodejs installation and introduction
- How to open a futures account safely? Which futures companies are more reliable now?
- 全技术栈、全场景、全角色云原生系列培训重磅首发,助力企业打造硬核云原生技术团队
- Four tips tell you how to use SMS to promote business sales?
- 配置服务器环境
猜你喜欢

Kalman filter -- Derivation from Gaussian fusion

Huaxing Securities: kitex practice under the original hybrid Cloud Architecture

Nodejs installation and introduction

ArcGIS无插件加载(无偏移)天地图

Video content production and consumption innovation

How to seamlessly transition from traditional microservice framework to service grid ASM

商业智能BI与业务管理决策思维之四:业务成本分析

法国A+ 法国VOC标签最高环保级别

程序员女友给我做了一个疲劳驾驶检测

【DesignMode】工厂模式 (factory pattern)
随机推荐
Regular expressions (regular matching)
The cloud native landing practice of using rainbow for Tuowei information
Business Intelligence BI and business management decision-making thinking 4: business cost analysis
Nodejs installation and introduction
Task04:集合运算-表的加减法和join等--天池龙珠计划SQL训练营学习笔记
20200525 Biotechnology - Sichuan Normal University self taught Biotechnology (undergraduate) examination plan txt
【DesignMode】单例模式(singleton pattern)
MySQL modify data type_ MySQL modify field type [easy to understand]
Gateway服务网关
Pytorch learning (III)
教你Selenium 测试用例编写
Small notes - integer improvement (C language)
Development: how to install offline MySQL in Linux system?
go之web框架 iris
全技术栈、全场景、全角色云原生系列培训重磅首发,助力企业打造硬核云原生技术团队
RFFE中MIPI协议
拓维信息使用 Rainbond 的云原生落地实践
小小笔记-整型提升(C语言)
DTD modeling
Construction and practice of full stack code test coverage and use case discovery system