vue3基础---async/await
2023-03-31 10:43:27 时间
async/await
1. 什么是 async/await
async/await 是 ES8(ECMAScript 2017)引入的新语法,用来简化 Promise 异步操作。在 async/await 出
现之前,开发者只能通过链式 .then() 的方式处理 Promise 异步操作。示例代码如下:
import thenFs from 'then-fs' thenFs .readFile('./files/11.txt', 'utf8') .catch((err) => { console.log(err.message) }) .then((r1) => { console.log(r1) return thenFs.readFile('./files/2.txt', 'utf8') }) .then((r2) => { console.log(r2) return thenFs.readFile('./files/3.txt', 'utf8') }) .then((r3) => { console.log(r3) })
-
.then 链式调用的优点:解决了回调地狱的问题。
-
.then 链式调用的缺点:代码冗余、阅读性差、不易理解。
-
2. async/await 的基本使用
使用 async/await 简化 Promise 异步操作的示例代码如下:
import thenFs from 'then-fs' async function getAllFile() { const r1 = await thenFs.readFile('./files/1.txt', 'utf8') console.log(r1) const r2 = await thenFs.readFile('./files/2.txt', 'utf8') console.log(r2) const r3 = await thenFs.readFile('./files/3.txt', 'utf8') console.log(r3) } getAllFile()
3. async/await 的使用注意事项
① 如果在 function 中使用了 await,则 function 必须被 async 修饰
② 在 async 方法中,第一个 await 之前的代码会同步执行,await 之后的代码会异步执行
import thenFs from 'then-fs' console.log('A') async function getAllFile() { console.log('B') const r1 = await thenFs.readFile('./files/1.txt', 'utf8') console.log(r1) const r2 = await thenFs.readFile('./files/2.txt', 'utf8') console.log(r2) const r3 = await thenFs.readFile('./files/3.txt', 'utf8') console.log(r3) console.log('D') } getAllFile() console.log('C') //打印出来的结果为 A B C 111 222 222 D
相关文章
- 金融服务领域的大数据:即时分析
- 影响大数据、机器学习和人工智能未来发展的8个因素
- 从0开始构建一个属于你自己的PHP框架
- 如何将Hadoop集成到工作流程中?这6个优秀实践必看
- SEO公司使用大数据优化其模型的5种方法
- 关于Web Workers你需要了解的七件事
- 深入理解HTTPS原理、过程与实践
- 增强分析:数据和分析的未来
- PHP协程实现过程详解
- AI专家:大数据知识图谱——实战经验总结
- 关于PHP的错误机制总结
- 利用数据分析量化协同过滤算法的两大常见难题
- 怎么做大数据工作流调度系统?大厂架构师一语点破!
- 2019大数据处理必备的十大工具,从Linux到架构师必修
- OpenCV中的KMeans算法介绍与应用
- 教大家如果搭建一套phpstorm+wamp+xdebug调试PHP的环境
- CentOS下三种PHP拓展安装方法
- Go语言HTTP Server源码分析
- Go语言HTTP Server源码分析
- 2017年4月编程语言排行榜:Hack首次进入前五十