Js 为什么需要「异步」呀 ?

因为由于 Js 单线程,同一时间只能做一件事,导致一旦遇到等待,就会阻塞代码的向下继续执行

这是让人不甘心的,因为这时 CPU 空闲

所以需要异步(形式上是回调函数),不阻塞代码的向下继续执行

举个例子

在浏览器端运行如下代码

1
2
3
console.log(1)
alert(3) // 网页会在这一行卡住(因为等待用户的交互)
console.log(2)

如果你希望按照 1 2 3 的顺序输出,那么就不能让alert(3)阻塞代码的向下继续执行

所以使用异步的手段,改写成如下代码

1
2
3
4
5
6
7
console.log(1)

setTimeout(() => {
alert(3)
}, 0)

console.log(2)

在 web 开发中,常使用异步手段把网络请求处理好

比如

1
2
3
4
5
6
7
8
9
var oImg = document.createElement('img')

// 异步
oImg.onload = () => {
document.body.appendChild(oImg)
console.log('图片加载完成')
}

oImg.src = 'https://github.com/xxx.jpg'

(完)