简体   繁体   中英

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. Why wouldn't this work for a for...in loop though?

I'm using Node v10.13.0.

For some time now I have been using for...of loops in Javascript to perform async tasks inside a loop structure. 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.

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. 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. Every await inside an async function is like a yield in a generator. 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. If you read up on generator functions, you'll see that in a sense that is exactly parallel, yield can appear anywhere. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM