当前位置:网站首页>promise async和await的方法与使用
promise async和await的方法与使用
2022-06-30 10:42:00 【weifeng_bushileng】
1.promise 将程序从异步的执行变成同步的一个过程
比如可以写一个简单的程序来
<script type="text/javascript">
function one(){
return 'I am one'
}
function two(){
//模拟一下网络请求
setTimeout(()=>{
return 'I am two'
},3000)
}
function three(){
return 'I am three'
}
function run(){
console.log(one())
console.log(two())
console.log(three())
}
//调用一下run函数
run()
</script>
此时,打印的结果又由
I am one
I am two
I am three
变成了
I am one
undefined
I am three
是因为two有一个网络请求,但是此时是我没有输出结果的
是因为只有一个run方法,不会等到3秒之后再去执行一次的
要解决这个问题,需要把异步的执行变成同步的
需要改变function two
function two(){
//这是一个标准的promise方法,resolve是一个请求成功返回的,reject是请求失败所要返回的
return new Promise((resolve,reject)=>{
//在这里也是用一个setTimeout去模拟一个网络请求
setTimeout(()=>{
resolve ('I am two‘’)
},3000)
})
}
此时的状态就是
此时的状态 是因为没有声明,要让two执行之后 再去执行three
此时我们要把 run改变一下状态,是要声明里面是有promise请求的
async function run(){
console.log(one())
console.log( await two()) //这个意思就是等two执行完了之后,再去执行three
console.log(three())
}
他的输出结果就是,显示输出
I am one
等三秒之后输出
I am two
I am three

边栏推荐
- 中移OneOS开发板学习入门
- Wireguard simple configuration
- SQL必需掌握的100个重要知识点:汇总数据
- OLAP数据库引擎如何选型?
- [rust daily] the first rust monthly magazine on January 22, 2021 invites everyone to participate
- Lvgl 8.2 picture scaling and rotation
- 记一次ViewPager + RecyclerView的内存泄漏
- LVGL 8.2 Simple Image button
- 电化学氧气传感器寿命、工作原理及应用介绍
- SQL必需掌握的100个重要知识点:组合查询
猜你喜欢

Dell et Apple, deux entreprises de PC établies, se sont effondrées rapidement

Review of mathematical knowledge: curve integral of the second type

高通发布物联网案例集 “魔镜”、数字农业已经成为现实

Go zero micro Service Practice Series (VIII. How to handle tens of thousands of order requests per second)

Handler-源码分析

同事的接口文档我每次看着就头大,毛病多多。。。

MySQL export SQL script file

CP2112使用USB转IIC通信教学示例

Mysql database foundation: constraint and identification columns
![[STL source code analysis] iterator](/img/e8/7c69cf6e96ecfa053494397a21eff0.jpg)
[STL source code analysis] iterator
随机推荐
我们公司使用 7 年的这套通用解决方案,打通了几十个系统,稳的一批!
基于HAL库的LED驱动库
LVGL8.2 Simple Checkboxes
sCrypt 中的 ECDSA 签名验证
Anhui "requirements for design depth of Hefei fabricated building construction drawing review" was printed and distributed; Hebei Hengshui city adjusts the pre-sale license standard for prefabricated
LVGL 8.2 Checkboxes as radio buttons
LED driver library based on Hal Library
深潜Kotlin协程(十六):Channel
Qt之实现动效导航栏
DataX JSON description
Handler-源码分析
【leetcode 239】滑动窗口
在IPhone12的推理延迟仅为1.6 ms!Snap等详析Transformer结构延迟,并用NAS搜出移动设备的高效网络结构...
ESP32-C3入门教程 问题篇⑨——Core 0 panic‘ed (Load access fault). Exception was unhandled. vfprintf.c:1528
LVGL 8.2 Simple Colorwheel
[rust weekly database] num bigint - large integer
运动App如何实现端侧后台保活,让运动记录更完整?
[rust daily] the first rust monthly magazine on January 22, 2021 invites everyone to participate
Matplotlib notes: contour & Contour
时间复杂度与空间复杂度