欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多个Promise顺序执行的解决思路

程序员文章站 2022-06-09 20:04:18
...

问题:多个延时器顺序执行,依次打印

function a() {
	setTimeout(() => {
		console.log(1)
	}, 200)
}

function b() {
	setTimeout(() => {
		console.log(2)
	}, 10)
}

function c() {
	setTimeout(() => {
		console.log(3)
	}, 30)
}

// a()
// b()
// c()
// console.log(4)

解决方案

function a() {
	return new Promise((resolve, reject) => {
		setTimeout(resolve, 200, 1)
	})
}

function b() {
	return new Promise((resolve, reject) => {
		setTimeout(resolve, 10, 2)
	})
}

function c() {
	return new Promise((resolve, reject) => {
		setTimeout(resolve, 30, 3)
	})
}

1. 使用回调函数解决

a().then(res => {
	console.log(res)
	b().then(res => {
		console.log(res)
		c().then(res => {
			console.log(res)
			console.log(4)
		})
	})
})

2. 使用promise/then链式调用

Promise.resolve().then(() => a())
.then(res => console.log(res))
.then(() => b())
.then(res => console.log(res))
.then(() => c())
.then(res => console.log(res))
.then(() => console.log(4))

3. 使用async/await解决

async function log(a, b, c) {
	const args = [].slice.call(arguments, 0)
	for (let item of args) {
		let res = await item()
		console.log(res)
	}
	console.log(4)
}
log(a, b, c)