当前位置:网站首页>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>
结果:
边栏推荐
- CAN/以太网转换器 CAN与以太网互联互通
- 1815. Get the maximum number of groups of fresh donuts state compression
- 【FPGA教程案例49】控制案例1——基于FPGA的PID控制器verilog实现
- 利用Navicat Premium导出数据库表结构信息至Excel
- ALSA音频架构
- Clang Code Model: Error: The clangbackend executable “X:/clangbackend.exe“ could not be started
- Where can machine learning be applied?What is machine learning useful for?
- 交换机和路由器技术-25-OSPF多区域配置
- 澳大利亚网络空间安全体系建设论析
- Events and scheduled tasks in Mysql
猜你喜欢

es-head plugin insert query and conditional query (5)

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

The principle, architecture, implementation, practice of "transfer" and "search", no need to be afraid of interviews

【深度学习】基于卷积神经网络的天气识别训练

findViewById返回null的问题

如何给网页添加icon图标?

【人话版】WEB3将至之“权益的游戏”

交换机和路由器技术-26-OSPF末梢区域配置

Self-research capability was recognized again, and Tencent Cloud Database was included in the Forrester Translytical report

梅克尔工作室--OpenEuler培训笔记(1)
随机推荐
洛谷P4560 Wall 砖墙
Merkel Studio--OpenEuler Training Notes (1)
Word2021 中的图片保存后就变模糊了
The principle, architecture, implementation, practice of "transfer" and "search", no need to be afraid of interviews
堆排序 和冒泡排序
LeetCode814 Math Question Day 15 Binary Tree Series Value "814 Binary Tree Pruning"
FPGA工程师面试试题集锦121~130
2022新员工公司级安全教育基础培训(118页)
Introduction to c # a week of high-level programming c # - LINQ Day Four
我的LaTeX入门
JVM 垃圾回收的概述与机制
交换机和路由器技术-31-扩展ACL
send_sig: 内核执行流程
Jetson Orin平台4-16路 GMSL2/GSML1相机采集套件推荐
干货:服务器网卡组技术原理与实践
Where can machine learning be applied?What is machine learning useful for?
如何缓解压力、拒绝内耗【1】
Overview of the JVM garbage collection and mechanism
交换机和路由器技术-36-端口镜像
源代码加密技术浅析