简体   繁体   English

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

[英]Vscode extension use variable outside of function

Hello within a vscode extension.js I cannot use the variable "chunk" outside of the function it is inside of: 您好在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: (tried to make a global variable, but I fail so much at javascript, is this supposed to 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*/

It doesn't work for two reasons. 它不起作用有两个原因。 First of all, function arguments are local to the function they belong to: 首先,函数参数是它们所属函数的局部变量:

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

Secondly, http.get() starts fetching the URL in another thread and continues executing the rest of the program, ie it calls vscode.window.showInformationMessage() immediately. 其次, http.get()开始在另一个线程中获取URL,并继续执行程序的其余部分,即它立即调用vscode.window.showInformationMessage() The variable does not even exist yet so, even if you didn't have scope issues, there would be nothing to print. 该变量甚至还不存在,因此,即使您没有范围问题,也不会打印任何内容。 Then, some time later (even if only a few milliseconds) the GET request completes. 然后,一段时间后(即使只有几毫秒),GET请求也会完成。 If it succeeded then function(chunk) {} gets finally called—too late! 如果成功,那么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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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