[英]Why can I use await keyword inside a for...of loop
EDIT: Please read carefully.编辑:请仔细阅读。 This does work.
这确实有效。 I'm trying to understand exactly why.
我想弄清楚为什么。
EDIT 2: I know that async makes things asynchronous.编辑 2:我知道异步使事情变得异步。 Why wouldn't this work for a for...in loop though?
为什么这对 for...in 循环不起作用?
I'm using Node v10.13.0.我正在使用节点 v10.13.0。
For some time now I have been using for...of loops in Javascript to perform async tasks inside a loop structure.一段时间以来,我一直在 Javascript 中使用 for...of 循环在循环结构内执行异步任务。 I have no doubt that it's working as expected.
我毫不怀疑它按预期工作。
I just ran across a situation where I have to explain why this is working, and realized that I actually have no idea.我刚遇到一种情况,我必须解释为什么这是有效的,并意识到我实际上不知道。 Here's a convoluted example just to help visualize what I mean:
这是一个复杂的例子,只是为了帮助形象化我的意思:
async function myFunc(array) {
for (var item of array) {
await asyncRequest();
}
}
In this function, it doesn't really matter what array
and asyncRequest
are, the point is that for each item in the array, program execution performs each asyncRequest
in a seemingly-sequential way before moving past the loop.在这个 function 中,
array
和asyncRequest
是什么并不重要,关键是对于数组中的每一项,程序执行在通过循环之前以看似连续的方式执行每个asyncRequest
。
I looked at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of , where I found that the for...of loop iterates over iterable objects.我查看了https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of ,在那里我发现 for...of 循环迭代可迭代对象。 Well, an array is definitely iterable but that fact seems unrelated.
好吧,一个数组绝对是可迭代的,但这个事实似乎无关紧要。
Any insight into this behavior?对这种行为有任何见解吗?
The async
and await
mechanism is implemented by combining Promises with generator functions. async
和await
机制是通过将 Promises 与生成器函数相结合来实现的。 Every await
inside an async
function is like a yield
in a generator. async
function 中的每个await
就像生成器中的yield
。 The transformation of the code is handled when the code is parsed, so you don't have to mess with all that yourself.代码的转换是在解析代码时处理的,因此您不必自己搞砸所有这些。
What that means is that inside an async
function, await
can appear anywhere : as you know, inside for... of
loops, but also inside for... in
loops, plain old for
loops, while
loops, whatever.这意味着在
async
function 中, await
可以出现在任何地方:如您所知,在for... of
循环中,但也在for... in
循环中,普通的for
循环, while
循环等等。 If you read up on generator functions, you'll see that in a sense that is exactly parallel, yield
can appear anywhere.如果你读过生成器函数,你会发现在某种意义上完全平行,
yield
可以出现在任何地方。 So for... of
loops are in no way special, and (as you suspect) their behavior and semantics have nothing to do with what await
means inside the body of such a loop.所以
for... of
循环绝不是特殊的,并且(如您所怀疑的那样)它们的行为和语义与await
在这种循环体内的含义无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.