当前位置:网站首页>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>
结果:
边栏推荐
猜你喜欢

Word2021 中的图片保存后就变模糊了

Three 】 【 yolov7 series of actual combat from 0 to build training data sets

梅克尔工作室--OpenEuler培训笔记(1)

分层架构&SOA架构

0 Basic software test for career change, self-study for 3 months, 12k*13 salary offer

"125 Palindrome Verification" of the 10th day string series of LeetCode brushing questions

Jetson Orin platform 4-16 channel GMSL2/GSML1 camera acquisition kit recommended

zabbix构建企业级监控告警平台

"239 Sliding Window Maximum Value" on the 16th day of LeetCode brushing

校园兼职平台项目反思
随机推荐
[Server installation Redis] Centos7 offline installation of redis
关于pom.xml文件
交换机和路由器技术-28-OSPF的NSSA区域
交换机和路由器技术-31-扩展ACL
Redis: Solve the problem of modifying the same key with distributed high concurrency
1815. 得到新鲜甜甜圈的最多组数 状态压缩
【深度学习】基于卷积神经网络的天气识别训练
洛谷P4324 扭动的回文串
洛谷P6586 蒟蒻火锅的盛宴
论文笔记:BBN: Bilateral-Branch Network with Cumulative Learningfor Long-Tailed Visual Recognition
To break the bottleneck of transactional work, the gentleman signs the electronic contract to release the "source power" of HR!
交换机和路由器技术-24-OSPF单区域配置
The shortest path out of the maze
Where can machine learning be applied?What is machine learning useful for?
洛谷P2150 寿司晚宴
一种基于共识机制的数字集群终端防失控方案研究
(转)JVM中那些区域会发生OOM?
校园兼职平台项目反思
走出迷宫的最短路径
Clang Code Model: Error: The clangbackend executable “X:/clangbackend.exe“ could not be started