I'm trying to delete a bunch of temp files that were created during a dispose function in a Visual Studio Code extension. For some reason a forEach
that initiates a bunch of async work is returning before that work is done even though I have await
in front of it. Is my problem with the understanding of forEach
, await
or the work being done within the individual dispose
functions?
public async dispose(): Promise<any> {
return new Promise(async (err) => {
await this.disposables.forEach(async disposable => {
await disposable.dispose();
});
this.disposables.clear();
let rmdir = promisify(fs.rmdir);
let tempDir = this.getTempDir();
try {
await rmdir(tempDir);
} catch (err) {
try {
this.outChannel.appendLine(`Error deleting ${tempDir}: ${err}.`);
} catch (err2) { }
}
});
}
The content of disposables is created with this code:
this.disposables.set(relativePath, {dispose: async () => {
let unlink = promisify(fs.unlink);
let rmdir = promisify(fs.rmdir);
let readdir = promisify(fs.readdir);
try {
try {
this.outChannel.appendLine(`Cleaning up ${tempFullPath}...`);
} catch(err2) { }
await unlink(tempFullPath);
relativePath = path.dirname(relativePath);
while (/[^\\\.]+/.test(relativePath)) {
let parent = path.join(tempDir,relativePath);
if ((await readdir(parent)).length === 0) {
await rmdir(parent);
}
relativePath = path.dirname(relativePath);
}
} catch (err) {
try {
this.outChannel.appendLine(`Failed - ${err}.`);
} catch(err3) { }
}
return;
}});
The result is that the final rmdir
in the highest dispose is failing because the the directory isn't empty even though it is by the time I go look.