当前位置:网站首页>async(异步)和await的使用
async(异步)和await的使用
2022-08-11 04:47:00 【qq_46302247】
正确使用方法:
<script>
let a = []
async function fun(){
console.log('开始喽!');
await interface()
console.log(a,'9999');
}
function interface() {
return new Promise((resolve, reject)=>{
setTimeout(()=>{
a = [1,9,22,6]
console.log('已经获取到接口数据!');
resolve()
},2000)
})
}
fun();
</script>
结果:
正常情况下,代码是同步执行的;例如,在函数A的内部调用函数B,要等内部函数B执行完成后,才会执行函数A中在函数B后面的代码。
<script>
let a = []
function fun(){
console.log('开始喽!');
interface()
console.log(a,'9999');
}
function interface() {
for(let i=0; i<10;i++) {
console.log(i);
}
a = [1,9,22,6]
}
fun();
</script>
结果:
但是当函数interface中需要调接口时(我是用setTimeout模拟调接口),此时函数fun中的代码就不是同步执行,而是异步了
<script>
let a = []
function fun(){
console.log('开始喽!');
interface()
console.log(a,'9999');
}
function interface() {
setTimeout(()=>{
a = [1,9,22,6]
console.log('已经获取到接口数据!');
},2000)
}
fun();
</script>
结果:
边栏推荐
猜你喜欢

Embedded Sharing Collection 33

论文笔记:BBN: Bilateral-Branch Network with Cumulative Learningfor Long-Tailed Visual Recognition

form表单提交数据库中文变成问号

交换机和路由器技术-22/23-OSPF动态路由协议/链路状态同步过程

洛谷P2150 寿司晚宴

To break the bottleneck of transactional work, the gentleman signs the electronic contract to release the "source power" of HR!

《卫星界》刊评“星辰大海”计划:孙宇晨为太空旅游带来新的机遇

ALSA音频架构 -- snd_pcm_open函数分析

"3 Longest Substring Without Repeating Characters" on the 17th day of LeetCode brushing

交换机和路由器技术-30-标准ACL
随机推荐
1815. Get the maximum number of groups of fresh donuts state compression
Jetson Orin platform 4-16 channel GMSL2/GSML1 camera acquisition kit recommended
"3 Longest Substring Without Repeating Characters" on the 17th day of LeetCode brushing
Mysql:设置主键自动增长起始值
[Server installation mysql] Use mysql offline installation package to install mysql5.7 under centos7
findViewById返回null的问题
直播软件搭建,流式布局,支持单选、多选等
[Web3 series development tutorial - create your first NFT (9)] How to view your NFT in the mobile wallet
使用百度EasyDL实现施工人员安全装备检测
洛谷P7441 Erinnerung
CAD2020 打开错误报告 e06d7363h Exception at 13644F69h
自研能力再获认可,腾讯云数据库入选 Forrester Translytical 报告
-填涂颜色-
The shortest path out of the maze
Embedded Sharing Collection 33
Layered Architecture & SOA Architecture
【组成原理 九 CPU】
0基础转行软件测试,自学3个月,浅拿12k*13薪offer
堆排序 和冒泡排序
分层架构&SOA架构