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

Viewed 53

I develop a vscode extension and I want to take a value from a user and use it later. I use async/await because otherwise I don't get the promt input for the user.

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. Any ideas? Thank you in advance

1 Answers

Another case where using Typescript would help a lot to understand such code. With TS you would have to write explicitly what the function returns:

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"');
Related