当前位置:网站首页>ES6高级-async的用法
ES6高级-async的用法
2022-08-04 21:30:00 【吃鱼丸的申申】
作用:使我们的异步操作更加方便,它会返回一个Promise对象,async是Generator的语法糖。
如果async函数中有多个await,那么then函数会等待所有的await指令运行完才去执行,看下面的代码:
<body>
<script>
async function f() {
// 假设这是一次异步行为
let s = await 'hello';
// 假设这也是一次异步行为
let data = await s.split('');
return data;
}
f().then(v => console.log(v)).catch(e => console.log(e))
</script>
</body>
输出结果:
再来看下面这段代码:
<body>
<script>
async function f() {
await Promise.reject('出错了');
await Promise.resolve('hello');
}
f().then(v => console.log(v)).catch(e => console.log(e))
</script>
</body>
输出结果:
await有一个特点就是如果哪里返回的是失败就会不再往下执行,更改方法:
<body>
<script>
async function f() {
try {
await Promise.reject('出错了');
} catch (error) {
}
return await Promise.resolve('hello');
}
f().then(v => console.log(v)).catch(e => console.log(e))
</script>
</body>
再来看一个例子:
<body>
<script>
function testAwait() {
return new Promise((resolve) => {
setTimeout(function() {
console.log("testAwait");
resolve('sy!!!');
}, 1000);
});
}
async function helloAsync() {
return await testAwait();
console.log("helloAsync");
}
helloAsync().then(val => console.log(val));
</script>
</body>
输出结果:
边栏推荐
- dotnet 通过 WMI 获取系统安装软件
- 【2022杭电多校5 1003 Slipper】多个超级源点+最短路
- for 循环中的 ++i 与 i++
- SPSS-System Clustering Software Practice
- PowerCLi batch configuration of NTP
- dotnet enables JIT multi-core compilation to improve startup performance
- 如何将二叉搜索树转化为一个有序的双向链表(原树上修改)
- 使用堡塔应用管理器配置laravel队列方法
- [Teach you to use the serial port idle interrupt of the STM32HAL library]
- 2、字符集-编码-解码
猜你喜欢
如何根据“前序遍历,中序遍历”,“中序遍历,后序遍历”构建按二叉树
JdbcTemplate概述和测试
AXI interface application of Zynq Fpga image processing - the use of axi_lite interface
Re24:读论文 IOT-Match Explainable Legal Case Matching via Inverse Optimal Transport-based Rationale Ext
y87.第五章 分布式链路追踪系统 -- 分布式链路追踪系统起源(一)
【2022杭电多校5 1012题 Buy Figurines】STL的运用
链队
PyTorch Geometric (PyG) 安装教程
[Teach you to use the serial port idle interrupt of the STM32HAL library]
PowerCLi import license to vCenter 7
随机推荐
Common methods of js's new Function()
国际项目管理师PMP证书,值得考嘛?
Dotnet using WMI software acquisition system installation
AtCoder Beginner Contest 262 D - I Hate Non-integer Number
Spss-系统聚类软件实操
如何一键重装Win11系统 一键重装系统方法
y87.第五章 分布式链路追踪系统 -- 分布式链路追踪系统起源(一)
数字重塑客观世界,全空间GIS发展正当其时
Data warehouse (1) What is data warehouse and what are the characteristics of data warehouse
milvus配置相关
Named routes, the role of name in components
【2022牛客多校5 A题 Don‘t Starve】DP
dotnet compress Stream or file using lz4net
DSPE-PEG-Aldehyde,DSPE-PEG-CHO,磷脂-聚乙二醇-醛基一种疏水18碳磷脂
buu web
如何将二叉搜索树转化为一个有序的双向链表(原树上修改)
27.降维
【2022杭电多校5 1012题 Buy Figurines】STL的运用
unity2D横版游戏教程8-音效
PCBA scheme design - kitchen voice scale chip scheme