当前位置:网站首页>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>
结果:
边栏推荐
猜你喜欢
Layered Architecture & SOA Architecture
Word2021 中的图片保存后就变模糊了
Three 】 【 yolov7 series of actual combat from 0 to build training data sets
嵌入式分享合集33
交换机和路由器技术-35-NAT转PAT
交换机和路由器技术-26-OSPF末梢区域配置
Clang Code Model: Error: The clangbackend executable “X:/clangbackend.exe“ could not be started
To break the bottleneck of transactional work, the gentleman signs the electronic contract to release the "source power" of HR!
【组成原理 九 CPU】
I wrote some code in my resume, but I still can't pass the interview
随机推荐
交换机和路由器技术-28-OSPF的NSSA区域
The principle, architecture, implementation, practice of "transfer" and "search", no need to be afraid of interviews
分层架构&SOA架构
交换机和路由器技术-32-命名ACL
"239 Sliding Window Maximum Value" on the 16th day of LeetCode brushing
How to learn machine learning?machine learning process
一起Talk编程语言吧
Snap - rotate the smallest number of an array
Harvesting of radio frequency energy
Layered Architecture & SOA Architecture
【服务器安装Redis】Centos7离线安装redis
【组成原理 九 CPU】
ALSA音频架构 -- aplay播放流程分析
交换机和路由器技术-27-OSPF路由重分发
set_new_handler(0)是什么意思?有什么用?
洛谷P7441 Erinnerung
MQ框架应用比较
简历里写了会代码,却依然过不了面试这一关
Introduction to c # a week of high-level programming c # - LINQ Day Four
FPGA工程师面试试题集锦121~130