为什么在for…of循环中使用await关键字

我正在使用Node v10.13.0。

一段时间以来,我一直在使用Java中的for ... of循环在循环结构内执行异步任务。我毫不怀疑它正在按预期工作。

我遇到了一个情况,我必须解释为什么这样做,并意识到我实际上不知道。这是一个复杂的示例,只是为了帮助形象化我的意思:

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.

对这种行为有任何见解吗?

评论