简体   繁体   English

如何从 javascript 中的异步 function 中返回一个值?

[英]How to return a value out of an async function in javascript?

I develop a vscode extension and I want to take a value from a user and use it later.我开发了一个 vscode 扩展,我想从用户那里获取一个值并在以后使用它。 I use async/await because otherwise I don't get the promt input for the user.我使用 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();

it works like this but I want to do the term commands outside of the async function.它像这样工作,但我想在异步 function 之外执行术语命令。 Any ideas?有任何想法吗? Thank you in advance先感谢您

Another case where using Typescript would help a lot to understand such code.使用 Typescript 的另一种情况将有助于理解此类代码。 With TS you would have to write explicitly what the function returns:使用 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"');
}

With that in place it becomes obvious how to proceed with the returned values:有了这些,如何处理返回值就变得很明显了:

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 };
}

and then:接着:

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM