【发布时间】:2021-09-11 09:27:56
【问题描述】:
我正在使用vscode.window.showOpenDialog 编写一个 VSCode 扩展。它显示一个用于选择目录的对话框 (Windows)。除了 async/await 之外,代码都可以工作。它不等待对话框关闭。如何让函数 getDirectory 等待函数 showDialog 解析所选目录?
函数getDirectory 立即输出日志#1,无需等待函数showDialog。此时dir 为空。正如预期的那样,function showDialog() 在对话框关闭后记录 #2。
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);
}
控制台:
#1:
#2: c:\Path\To\Chosen\Directory
- 打字稿 4.3.2.
【问题讨论】:
-
您不是在等待
.showOpenDialog(),而是立即返回带有空字符串的已解析Promise。您已经在标题和脚本中添加了async/await。所以你应该已经知道如何“等待”.showOpenDialog()+ How to return the response from an asynchronous call? -
return vscode.window.showOpenDialog(options).then( /* ... /*)并在.then内部将dir = String(fileUri[0].fsPath);替换为return String(fileUri[0].fsPath); -
谢谢VLAZ。它终于奏效了!顺便说一句,建议的答案并不能解决问题。
-
@oivron 答案是关于如何使用 Promises 的解释
-
事实上,建议的答案确实有效。抱歉,是我的错。谢谢@Shuhaib zahir!
标签: typescript visual-studio-code vscode-extensions