Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

重学 JS:为啥 await 在 forEach 中不生效 #17

Open
KieSun opened this issue Apr 13, 2019 · 6 comments
Open

重学 JS:为啥 await 在 forEach 中不生效 #17

KieSun opened this issue Apr 13, 2019 · 6 comments

Comments

@KieSun
Copy link
Owner

KieSun commented Apr 13, 2019

这是重学 JS 系列的第三篇文章,写这个系列的初衷也是为了夯实自己的 JS 基础或者了解一些之前不知道的东西。既然是重学,肯定不会从零开始介绍一个知识点,如有遇到不会的内容请自行查找资料。

不知道你有没有写过类似的代码,反正以前我是写过

function test() {
	let arr = [3, 2, 1]
	arr.forEach(async item => {
		const res = await fetch(item)
		console.log(res)
	})
	console.log('end')
}

function fetch(x) {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve(x)
		}, 500 * x)
	})
}

test()

我当时期望的打印顺序是

3
2
1
end

结果现实与我开了个玩笑,打印顺序居然是

end
1
2
3

为什么?

其实原因很简单,那就是 forEach 只支持同步代码。

我们可以参考下 Polyfill 版本的 forEach,简化以后类似就是这样的伪代码

while (index < arr.length) {
		// 也就是我们传入的回调函数
		callback(item, index)
}

从上述代码中我们可以发现,forEach 只是简单的执行了下回调函数而已,并不会去处理异步的情况。并且你在 callback 中即使使用 break 也并不能结束遍历。

怎么解决?

一般来说解决的办法有两种。

第一种是使用 Promise.all 的方式

async function test() {
	let arr = [3, 2, 1]
	await Promise.all(
		arr.map(async item => {
			const res = await fetch(item)
			console.log(res)
		})
	)
	console.log('end')
}

这样可以生效的原因是 async 函数肯定会返回一个 Promise 对象,调用 map 以后返回值就是一个存放了 Promise 的数组了,这样我们把数组传入 Promise.all 中就可以解决问题了。但是这种方式其实并不能达成我们要的效果,如果你希望内部的 fetch 是顺序完成的,可以选择第二种方式。

另一种方法是使用 for...of

async function test() {
	let arr = [3, 2, 1]
	for (const item of arr) {
		const res = await fetch(item)
		console.log(res)
	}
	console.log('end')
}

这种方式相比 Promise.all 要简洁的多,并且也可以实现开头我想要的输出顺序。

但是这时候你是否又多了一个疑问?为啥 for...of 内部就能让 await 生效呢。

因为 for...of 内部处理的机制和 forEach 不同,forEach 是直接调用回调函数,for...of 是通过迭代器的方式去遍历。

async function test() {
	let arr = [3, 2, 1]
	const iterator = arr[Symbol.iterator]()
	let res = iterator.next()
	while (!res.done) {
		const value = res.value
		const res1 = await fetch(value)
		console.log(res1)
		res = iterator.next()
	}
	console.log('end')
}

以上代码等价于 for...of,可以看成 for...of 是以上代码的语法糖。

最后

以上就是本篇文章的全部内容了,如果你还有什么疑问欢迎在评论区与我互动。

我所有的系列文章都会在我的 Github 中最先更新,有兴趣的可以关注下。今年主要会着重写以下三个专栏

  • 重学 JS
  • React 进阶
  • 重写组件

最后,觉得内容有帮助可以关注下我的公众号 「前端真好玩」咯,会有很多好东西等着你。

@KieSun KieSun changed the title 重学 JS:为啥 await 不能用在 forEach 中 重学 JS:为啥 await 在 forEach 中不生效 Apr 13, 2019
@libin1991
Copy link

image

@libin1991
Copy link

应该是for循环,不是你说的那个Promise.all 的方式
image

@KieSun
Copy link
Owner Author

KieSun commented Apr 17, 2019

应该是for循环,不是你说的那个Promise.all 的方式
image

for 循环也是可以实现这样的功能的

@ZKHelloworld
Copy link

其实原因很简单,那就是 forEach 只支持同步代码。

原因感觉描述的不是很且当哈,参考

Each of the async callback function calls does return a promise, but you're throwing them away instead of awaiting them

@daryl-z
Copy link

daryl-z commented Jun 14, 2019

所以为什么打印的结果1,2,3

@hahaiamzd
Copy link

hahaiamzd commented Oct 8, 2019

所以为什么打印的结果1,2,3

因为在fetch函数里面setTimeout的时间做了操作

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants