当前位置:网站首页>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

边栏推荐
- 经典面试题:负责的模块,针对这些功能点你是怎么设计测试用例的?【杭州多测师】【杭州多测师_王sir】...
- LVGL 8.2 Image styling and offset
- When does the database need to use the index [Hangzhou multi surveyors] [Hangzhou multi surveyors _ Wang Sir]
- Deep dive kotlin Xie Cheng (17): Actor
- 运动App如何实现端侧后台保活,让运动记录更完整?
- 再测云原生数据库性能:PolarDB依旧最强,TDSQL-C、GaussDB变化不大
- Qt之实现动效导航栏
- SQL必需掌握的100个重要知识点:分组数据
- 文件共享服务器
- Jetpack Compose DropdownMenu跟随手指点击位置显示
猜你喜欢
![[STL source code analysis] container (to be supplemented)](/img/69/0c6e0e8ecb3ebc8c9b8503f5a8b4e5.jpg)
[STL source code analysis] container (to be supplemented)

ArrayList与顺序表

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

Viewing technological changes through Huawei Corps (V): smart Park

Machine learning interview preparation (I) KNN

Auto SEG loss: automatic loss function design

科普达人丨漫画图解什么是eRDMA?

pytorch 笔记 torch.nn.BatchNorm1d

国产自研系统的用户突破4亿,打破美国企业的垄断,谷歌后悔不迭

Wireguard simple configuration
随机推荐
LVGL 8.2 Checkboxes as radio buttons
MySQL导出sql脚本文件
基于HAL库的LED驱动库
LVGL 8.2 Checkboxes as radio buttons
The jetpack compose dropdownmenu is displayed following the finger click position
OLAP数据库引擎如何选型?
Matplotlib notes: contour & Contour
What is erdma as illustrated by Coptic cartoon?
煥發青春的戴爾和蘋果夾擊,兩大老牌PC企業極速衰敗
The precision problem of depth texture in unity shader - stepping pit - BRP pipeline (there is no solution, it is recommended to replace URP)
iptables目标TPROXY
Foresniffer tutorial: extracting data
LeetCode Algorithm 86. Separate linked list
第一届中国数字藏品大会即将召开
内存逃逸分析
LVGL 8.2 menu from a drop-down list
运动App如何实现端侧后台保活,让运动记录更完整?
200000 bonus pool! [Alibaba security × ICDM 2022] the risk commodity inspection competition on the large-scale e-commerce map is in hot registration
Pandora IOT development board learning (HAL Library) - Experiment 1 running lantern (RGB) experiment (learning notes)
Machine learning interview preparation (I) KNN