[英]How to return a value out of an async function in javascript?
我開發了一個 vscode 擴展,我想從用戶那里獲取一個值並在以后使用它。 我使用 async/await 因為否則我不會為用戶獲得提示輸入。
async function input() {
const destBranch = await vscode.window.showInputBox({ placeHolder: 'Insert the name of the destination branch' });
const devBranch = await vscode.window.showInputBox({ placeHolder: 'Insert the name of the Developing branch' });
const term = vscode.window.createTerminal("gitTerminal");
term.show();
term.sendText('git switch ' + destBranch);
term.sendText('git checkout ' + devBranch + ' file.txt');
term.sendText('git add .');
term.sendText('git commit -m "tests"');
};
input();
它像這樣工作,但我想在異步 function 之外執行術語命令。 有任何想法嗎? 先感謝您
使用 Typescript 的另一種情況將有助於理解此類代碼。 使用 TS,您必須明確寫出 function 返回的內容:
async function input(): Promise<void> {
const destBranch = await vscode.window.showInputBox({ placeHolder: 'Insert the name of the destination branch' });
const devBranch = await vscode.window.showInputBox({ placeHolder: 'Insert the name of the Developing branch' });
const term = vscode.window.createTerminal("gitTerminal");
term.show();
term.sendText('git switch ' + destBranch);
term.sendText('git checkout ' + devBranch + ' file.txt');
term.sendText('git add .');
term.sendText('git commit -m "tests"');
}
有了這些,如何處理返回值就變得很明顯了:
interface Branches {
destBranch: string;
devBranch: string;
}
async function input(): Promise<Branches> {
const destBranch = await vscode.window.showInputBox({ placeHolder: 'Insert the name of the destination branch' });
const devBranch = await vscode.window.showInputBox({ placeHolder: 'Insert the name of the Developing branch' });
return { devBranch, destBranch };
}
接着:
const branches = await input();
const term = vscode.window.createTerminal("gitTerminal");
term.show();
term.sendText('git switch ' + branches.destBranch);
term.sendText('git checkout ' + branches.devBranch + ' file.txt');
term.sendText('git add .');
term.sendText('git commit -m "tests"');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.