当前位置:网站首页>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
边栏推荐
- LVGL 8.2 Image styling and offset
- LeetCode Algorithm 86. 分隔鏈錶
- Matplotlib notes: contour & Contour
- [leetcode 16] sum of three numbers
- 训练一个图像分类器demo in PyTorch【学习笔记】
- LVGL 8.2 menu from a drop-down list
- SQL必需掌握的100个重要知识点:组合查询
- LVGL 8.2 Image
- 国产自研系统的用户突破4亿,打破美国企业的垄断,谷歌后悔不迭
- The life, working principle and application of electrochemical oxygen sensor
猜你喜欢
Kotlin 协程调度切换线程是时候解开谜团了
List介绍
电化学氧气传感器寿命、工作原理及应用介绍
sCrypt 中的 ECDSA 签名验证
Time complexity and space complexity
Mysql database foundation: constraint and identification columns
China will force a unified charging interface. If Apple does not bow its head, iPhone will be kicked out of the Chinese market
The jetpack compose dropdownmenu is displayed following the finger click position
高通发布物联网案例集 “魔镜”、数字农业已经成为现实
Deep dive kotlin synergy (18): hot and cold data flow
随机推荐
同事的接口文档我每次看着就头大,毛病多多。。。
时间复杂度与空间复杂度
ArrayList and sequence table
200000 bonus pool! [Alibaba security × ICDM 2022] the risk commodity inspection competition on the large-scale e-commerce map is in hot registration
LeetCode Algorithm 86. 分隔鏈錶
Cp2112 teaching example of using USB to IIC communication
国产自研系统的用户突破4亿,打破美国企业的垄断,谷歌后悔不迭
文件共享服务器
语音识别-基础(一):简介【语音转文本】
Mysql database foundation: TCL transaction control language
LVGL 8.2 Checkboxes as radio buttons
ESP32-C3入门教程 IoT篇⑤——阿里云 物联网平台 EspAliYun RGB LED 实战之批量生产的解决方案
LED driver library based on Hal Library
Dickinson's soul chooses its companion
LVGL 8.2图片缩放及旋转
Matplotlib notes: contour & Contour
SQL必需掌握的100个重要知识点:更新和删除数据
SQL必需掌握的100个重要知识点:使用表别名
How can the sports app keep the end-to-side background alive to make the sports record more complete?
Unity Shader - 踩坑 - BRP 管线中的 depth texture 的精度问题(暂无解决方案,推荐换 URP)