Vscode 扩展在函数外使用变量

Vscode extension use variable outside of function

你好 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*/

编辑:(试图创建一个全局变量,但我在 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*/

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

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