VSCode扩展在函数外部使用变量

时间:2018-09-13 14:16:01

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

vscode extension.js中的问候你好,我不能在函数内部使用变量“ chunk”:

let http = require('http');
let keyname = "key.key";
http.get('http://mysite.nl/vscode/?with=data', function(res) {
  res.on("data", function(chunk) {
    vscode.window.showInformationMessage("INSIDE: " + chunk);
  });
});
vscode.window.showInformationMessage("OUSIDE FUNCTION:" + chunk); /*this does not work*/

edit :(试图创建一个全局变量,但是我在javascript上失败了很多,这应该可以吗?)

let globalvar;
let http = require('http');
let keyname = "key.key";
http.get('http://mysite.nl/vscode/?with=data', function(res) {
  res.on("data", function(chunk) {
    vscode.window.showInformationMessage("INSIDE: " + chunk);
    globalvar = chunk;
  });
});
vscode.window.showInformationMessage("OUSIDE FUNCTION:" + globalvar); /*this does not work*/

1 个答案:

答案 0 :(得分:1)

它不起作用有两个原因。首先,函数参数是它们所属函数的局部变量:

function foo(bar) {
    console.log("Inside function: %s", typeof bar);
    function inner(){
      console.log("In function's scope: %s", typeof bar);
    }
    inner();
}

foo("Hi");
console.log("Elsewhere: %s", typeof bar);

第二,http.get()开始在另一个线程中获取URL,并继续执行程序的其余部分,即它立即调用vscode.window.showInformationMessage()。该变量甚至还不存在,因此,即使您没有范围问题,也不会打印任何内容。然后,一段时间后(即使只有几毫秒),GET请求也会完成。 如果成功,那么function(chunk) {}最终会被调用-为时已晚!

let globalvar;
window.setTimeout(function (chunk){
    console.log("Done! Chunk is %s", chunk);
    globalvar = chunk;
}, 2000, "Hi!");
console.log("Chunk? %s", typeof globalvar);