[英]How to make a global variable within a npm package function
Im using npm papercut https://www.npmjs.com/package/papercut and I want to get access to a variable value that is within a papercut function. 我正在使用npm papercut https://www.npmjs.com/package/papercut ,我想访问papercut函数中的变量值。 This is what I have so far.
到目前为止,这就是我所拥有的。
I want to get access to the value of the variable Img outside the function to the variable NewImg here Im trying to do so using a global variable. 我想在函数外部访问变量Img的值,这里的变量NewImg我试图使用全局变量来实现。 Anyone see my problem or have any suggestions.
任何人看到我的问题或有任何建议。
var NewImg = {} uploader.process('image1', file.path, function(images){ var Img = images.avatar NewImg.input = Img console.log(Img); }) console.log(NewImg.input)
this logs out undefined 这注销未定义
Looks like some asynchronous code. 看起来像一些异步代码。 It's likely that the callback isn't called before your
console.log()
so your NewImg.input
is undefined. 可能未在
console.log()
之前调用回调,因此您的NewImg.input
是未定义的。
Also var NewImg.input = Img
is not syntactically correct, remove var
. 同样,
var NewImg.input = Img
在语法上不正确,请删除var
。
Read more about asynchronous javascript: Asynchronous Javascript 阅读有关异步javascript的更多信息: 异步Javascript
var NewImg = {}
uploader.process('image1', file.path, function(images){
// I'm a callback function in an asynchronous method!
// I will run sometime in the future!
var Img = images.avatar
NewImg.input = Img
console.log(Img);
})
// Oh no! I ran before the callback function in the *asynchronous* method above, before NewImg.input is assigned any value
console.log(NewImg.input)
If you use var
inside a function, then you make new variable inside the function with the same name. 如果在函数内部使用
var
,则在函数内部使用相同的名称创建新变量。 So your code should be: 因此,您的代码应为:
var NewImg = {}
uploader.process('image1', file.path, function(images){
var Img = images.avatar;
NewImg.input = Img;
console.log(Img);
console.log(NewImg.input)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.