-
Notifications
You must be signed in to change notification settings - Fork 124
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
Comments
原因感觉描述的不是很且当哈,参考:
|
所以为什么打印的结果1,2,3 |
因为在fetch函数里面setTimeout的时间做了操作 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
不知道你有没有写过类似的代码,反正以前我是写过
我当时期望的打印顺序是
结果现实与我开了个玩笑,打印顺序居然是
为什么?
其实原因很简单,那就是
forEach
只支持同步代码。我们可以参考下 Polyfill 版本的
forEach
,简化以后类似就是这样的伪代码从上述代码中我们可以发现,
forEach
只是简单的执行了下回调函数而已,并不会去处理异步的情况。并且你在callback
中即使使用break
也并不能结束遍历。怎么解决?
一般来说解决的办法有两种。
第一种是使用
Promise.all
的方式这样可以生效的原因是
async
函数肯定会返回一个Promise
对象,调用map
以后返回值就是一个存放了Promise
的数组了,这样我们把数组传入Promise.all
中就可以解决问题了。但是这种方式其实并不能达成我们要的效果,如果你希望内部的fetch
是顺序完成的,可以选择第二种方式。另一种方法是使用
for...of
这种方式相比
Promise.all
要简洁的多,并且也可以实现开头我想要的输出顺序。但是这时候你是否又多了一个疑问?为啥
for...of
内部就能让await
生效呢。因为
for...of
内部处理的机制和forEach
不同,forEach
是直接调用回调函数,for...of
是通过迭代器的方式去遍历。以上代码等价于
for...of
,可以看成for...of
是以上代码的语法糖。最后
以上就是本篇文章的全部内容了,如果你还有什么疑问欢迎在评论区与我互动。
我所有的系列文章都会在我的 Github 中最先更新,有兴趣的可以关注下。今年主要会着重写以下三个专栏
最后,觉得内容有帮助可以关注下我的公众号 「前端真好玩」咯,会有很多好东西等着你。
The text was updated successfully, but these errors were encountered: