I am writing a VSCode extension using vscode.window.showOpenDialog
. It shows a dialog for choosing a directory (Windows). The code works except for the async/await. It's not waiting for the dialog to close. How can I make function getDirectory wait for function showDialog to resolve the chosen directory?
Function getDirectory outputs log #1 immediately without waiting for function showDialog. At this point dir
is empty. As expected, function showDialog()
logs #2 after the dialog is closed.
extension.ts:
async function getDirectory(): Promise<void> {
const dir = await showDialog();
console.log("#1: " + String(dir)); //Outputs before dialog is closed.
}
function showDialog() {
let dir = "";
const options: vscode.OpenDialogOptions = {
canSelectMany: false,
openLabel: 'Select',
canSelectFiles: false,
canSelectFolders: true
};
vscode.window.showOpenDialog(options).then(fileUri => {
if (fileUri && fileUri[0]) {
console.log('#2: ' + fileUri[0].fsPath); //Outputs when dialog is closed.
dir = String(fileUri[0].fsPath);
}
});
return Promise.resolve(dir);
}
Console:
#1:
#2: c:\Path\To\Chosen\Directory
- Typescript 4.3.2.