【问题标题】:Correct Way to Call InputBox with Async/Await in VS Code在 VS Code 中使用 Async/Await 调用 InputBox 的正确方法
【发布时间】:2019-02-15 16:13:22
【问题描述】:

在我正在编写的 VS Code 扩展中,我试图了解使用带有 await 的异步函数的正确方法,以便从呈现给用户的输入框中获取数据。

我的代码的主要部分没有像我想象的那样工作:

function runGitConfigCheck() {
    console.log('\nChecking for .gitconfig file');
    let requiredgitTags = ['user', 'http', 'https', 'core'];
    let requiredgitConfigItems = 
    [
    'http.sslbackend=thebestSSLofcourse',
    'http.proxy=http://myproxy.website.example:1234',
    'https.proxy=http://myproxy.website.example:1234',
    'http.sslcainfo=C:\\Users\\myusername\\path\\to\\folder'
    ];
    /** 
        TODO: other things here
     */

    let gitConfigExists: boolean = checkFileExistsInTargetFolder(userProfile, '\\.gitconfig');
    if (gitConfigExists === false) {
        // create new empty git config
        fs.appendFileSync(userProfile + '\\.gitconfig', '');
        requiredgitConfigItems.forEach(function (value) {
            console.log('Writing value to config: ' + value);
            fs.appendFileSync(userProfile + '\\.git', '\n' + value);
        });
    }
    else if (gitConfigExists === true) {
        console.log('.gitconfig file found');
        var gitconfig = ini.parse(fs.readFileSync(userProfile+"\\.gitconfig",'utf-8'));
        let attributes = getGitConfigAttributeNames(gitconfig);

        // check for the [user], [http], [https], and [core] attributes
        let tagsNotFound = new Array();
        let tagsFound = new Array();

        for (var tag in requiredgitTags) {
            let tagValue = requiredgitTags[tag];
            console.log('searching for tag '+tagValue);
            let search = searchForGitTag(tagValue, attributes);

            if(search === true) {
                tagsFound.push(tagValue);
            }
            else {
                tagsNotFound.push(tagValue);
            }
        }

        addGitTagsNotFound(tagsNotFound, userProfile+'\\.gitconfig');

        console.log('Finished doing all the things!');
    }   
}


function appendItemsToConfigFile(file: fs.PathLike, configItems: string[], firstItemStartsNewLine?: boolean)
{
    let counter: number = 0;
    configItems.forEach(function (item) {
        if(firstItemStartsNewLine === true && counter === 0) {
            fs.writeFileSync(file, `\n${item}\n`, {encoding: 'utf-8', flag: 'as'});
        }
        else {
            fs.writeFileSync(file, `${item}\n`, {encoding: 'utf-8', flag: 'as'});
        }
        counter++;
    });
    return;
}

async function getUserInfo(myplaceholder: string) {
    let userInputWindow = vscode.window.showInputBox({ placeHolder: myplaceholder, prompt: 'Here is the prompt' });
    return userInputWindow;
}

function addGitTagsNotFound(tags: string[], configFile: fs.PathLike) {
    tags.forEach(function (tag) {
        switch(tag) {
            case 'user':
                let currentName = getUserInfo('Message1')
                .then(function (result) {
                    return result;
                });
                let currentEmail = getUserInfo('Message2')
                .then(function (result) {
                    return result;
                });
                console.log(currentEmail + ' ' currentEmail);
                break;
            case 'http':
                console.log('Adding config items for [http] tag');
                appendItemsToConfigFile(configFile, [`[${tag}]`,
                                                    '\tsslBackend=myconfig',
                                                    `\tsslCAInfo=${userProfile}\\path\\to\\folder`,
                                                    '\tproxy=http://myproxy.website.example:1234'], true);
                break;
            case 'https':
                console.log('Adding config items for [https] tag');
                appendItemsToConfigFile(configFile, [`[${tag}]`,
                                                    `\tsslCAInfo=${userProfile}\\path\\to\\folder`,
                                                    '\tproxy=proxy=http://myproxy.website.example:1234'], true);
                break;
            case 'core':
                console.log('Adding config items for [core] tag');
                appendItemsToConfigFile(configFile, [`[${tag}]`,
                                                    `\teditor=${userProfile}\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe -w`], true);
                break;
        }
    });
}

当使用数组和文件调用 addGitTagsNotFound() 时,输入框仅在函数 runGitConfigCheck() 的其余部分在扩展的父函数 activate() 中完成后才会出现。

我认为我只是没有正确理解 async/await,并且由于我正在同步附加到配置文件,我的猜测是它阻止了输入框弹出。

谁能帮我解释一下,我将不胜感激!

【问题讨论】:

    标签: typescript visual-studio-code vscode-extensions


    【解决方案1】:

    我在寻找类似问题时进入了这个问题。 基本上你应该向 addGitTagsNotFound 函数添加异步前缀 并在每次调用异步函数时添加等待:vscode.window.showInputBox() 和 getUserInfo()

    工作示例:

    async function getUserInfo(myplaceholder: string) {
        let userInputWindow =  await vscode.window.showInputBox({ placeHolder: myplaceholder, prompt: 'Here is the prompt' });
        return userInputWindow;
    }
    
    async function addGitTagsNotFound(tags: string[], configFile: fs.PathLike) {
        tags.forEach(function (tag) {
            switch(tag) {
                case 'user':
                    let currentName = await getUserInfo('Message1')
                    .then(function (result) {
                        return result;
                    });
                    let currentEmail = await getUserInfo('Message2')
                    .then(function (result) {
                        return result;
                    });
                    console.log(currentEmail + ' ' currentEmail);
                    break;
                case 'http':
                    console.log('Adding config items for [http] tag');
                    appendItemsToConfigFile(configFile, [`[${tag}]`,
                                                        '\tsslBackend=myconfig',
                                                        `\tsslCAInfo=${userProfile}\\path\\to\\folder`,
                                                        '\tproxy=http://myproxy.website.example:1234'], true);
                    break;
                case 'https':
                    console.log('Adding config items for [https] tag');
                    appendItemsToConfigFile(configFile, [`[${tag}]`,
                                                        `\tsslCAInfo=${userProfile}\\path\\to\\folder`,
                                                        '\tproxy=proxy=http://myproxy.website.example:1234'], true);
                    break;
                case 'core':
                    console.log('Adding config items for [core] tag');
                    appendItemsToConfigFile(configFile, [`[${tag}]`,
                                                        `\teditor=${userProfile}\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe -w`], true);
                    break;
            }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 2013-08-14
      • 1970-01-01
      • 2020-06-02
      • 2014-09-20
      • 2018-10-07
      相关资源
      最近更新 更多