【发布时间】:2019-08-18 05:41:31
【问题描述】:
我有一个函数。
function async extractTars (tarList) {
try {
for (let i = 0; i < tarList.length; i ++) {
// I need this loop to be sync but it isn't hitting the next iteration
return new Promise((resolve, reject) => {
fs.createReadStream(`${PATHS.TAR}/${tarList[i]}`)
.pipe(tar.extract(PATHS.GZ))
.on('error', err => reject(err))
.on('finish', () => resolve())
})
}
// What is the correct way to resolve this async fn? Should i just return or will it resolve anyway after the loop?
} catch (e) {
// handle error
}
}
由于某种原因,它永远不会到达循环的下一次迭代。我在这里想念什么?我怎样才能使这些类型的循环同步。在这个特定的项目中,我有很多循环需要在下一个之前完成。我已经尝试了几种我在这里看到的方法,但我显然遗漏了一些东西。
任何帮助将不胜感激!
【问题讨论】:
-
因为是返回值,把return语句换成await就行了
标签: node.js loops asynchronous