多个异步请求的执行顺序

shayloyuki / 2024-01-17 / 原文

Fn() {
	// 以下两个都为异步请求
	this.getData1()
	this.getData2()
}

this.Fn()

我以为的执行顺序是:getData1 --> getData2

但其实,顺序不一定,getData1 有时在前,有时在后。

解决:加上 async 和 await

async Fn() {
	// 以下两个都为异步请求
	await this.getData1()
	await this.getData2()
}

this.Fn()

参考链接

深入理解JavaScript的执行机制(同步和异步)