我创建了一个使用tar模块将文件压缩到tar存档中的文件的函数,但是由于其异步行为,我无法通过迭代执行多个函数。如何同步此功能?
我在文档中添加了sync:true选项,但无法正常工作
let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
tar
.c({
gzip: true,
file: path.resolve(
archivePath,
file + " - " + date.getTime() + ".tar.gz"
), //compressed file name
C: fullPath
},
["."]
)
.then(() => {
console.log({
status: 0,
message: "compressed - " + file
});
});
}
答案 0 :(得分:-1)
tar是异步的,因此您的循环不必等待下一次迭代的午餐了……
在tar命令的前面添加'await'关键字...
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
var result = await resolveAfter2Seconds();
console.log(result);
// expected output: 'resolved'
}
asyncCall();