当前位置:网站首页>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>输出结果:
边栏推荐
- 链栈的应用
- 传奇服务器需要什么配置?传奇服务器租用价格表
- mdk5.14 cannot be burned
- 可视化工作流引擎开发OA系统,让企业少花冤枉钱
- Red team kill-free development practice of simulated confrontation
- LayaBox---TypeScript---首次接触遇到的问题
- 27.降维
- How to understand the crawler's Scrapy framework in the simplest and most popular way?
- Hands-on Deep Learning_NiN
- 立方度量(Cubic Metric)
猜你喜欢
随机推荐
数电快速入门(五)(编码器的介绍以及通用编码器74LS148和74LS147的介绍)
【手把手教你使用STM32HAL库的串口空闲中断】
【编程思想】
数电快速入门(二)(复合逻辑运算和逻辑代数的基本定律的介绍)
实战:10 种实现延迟任务的方法,附代码!
buu web
dotnet 使用 lz4net 压缩 Stream 或文件
laravel whereDoesntHave
jekyll 在博客添加流程图
Common methods of js's new Function()
unity2D横版游戏教程8-音效
1.读写点云文件
js的new Function()常用方法
PowerCLi 批量配置NTP
PCBA方案设计——厨房语音秤芯片方案
visual studio 2015 warning MSB3246
大势所趋之下的nft拍卖,未来艺术品的新赋能
Data warehouse (1) What is data warehouse and what are the characteristics of data warehouse
《剑指offer》刷题分类
如何一键重装win7系统?重装win7系统详细教程









