async在await循环中使用是否有任何问题?我正在尝试循环遍历文件数组和forEach每个文件的内容.
import fs from 'fs-promise'
async function printFiles () {
const files = await getFilePaths() // Assume this works fine
files.forEach(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
})
}
printFiles()
Run Code Online (Sandbox Code Playgroud)
这段代码确实有效,但这可能会出错吗?我有人告诉我你不应该使用await这样的高阶函数,所以我只是想问一下这是否有任何问题.
我知道什么是for... in循环(它迭代密钥),但第一次听到for... of(它迭代值).我对for... of循环感到困惑.我没有得到.这是下面的代码:
var arr = [3, 5, 7];
arr.foo = "hello";
for (var i in arr) {
console.log(i); // logs "0", "1", "2", "foo"
}
for (var i of arr) {
console.log(i); // logs "3", "5", "7"
//it is does not log "3", "5", "7","hello"
}
Run Code Online (Sandbox Code Playgroud)
我得到的是,for... of迭代属性值.那么为什么它不记录(返回)"3", "5", "7","hello"而不是"3", "5", "7"?但for... in循环迭代每个键("0","1","2","foo").这里for... in循环也迭代foo密钥.但是对于...不是对foo财产价值的迭代,即"hello"为什么它是这样的?
简而言之:
在这里我控制台 …