简体   繁体   English

此JavaScript代码段的正确变量范围是什么

[英]What is the correct variable scope for this Javascript snippet

I have written the function below. 我已经在下面编写了函数。 I need to read the dimensions of an image and then scale it back. 我需要读取图像的尺寸,然后将其缩小。 After the initial callback I want to use the width and height values I've calculated to resize and save the image. 初始回调后,我想使用计算出的widthheight值来调整大小和保存图像。 My variables are out of scope though and I get a ReferenceError: width is not defined . 我的变量不在范围内,但出现了ReferenceError: width is not defined How do I correctly scope these variables so they are available to the resize function? 如何正确确定这些变量的范围,以便它们可用于resize功能?

  function saveImage(image) {
    return new Promise((resolve, reject) => {
      gm(image.data).size(function(error, value) {
        if (value.width > image.maxSize || value.height > image.maxSize) {
          max = Math.max(value.width, value.height);
          if (value.width == max) {
            width = image.maxSize; height = null;
          } else {
            height = image.maxSize; width = null;
          }
        } else {
          width = value.width; height = value.height;
        }
      })
      .resize(width, height)
      .write('./tmp/test.jpg', function(error, value) {
        if (!error) console.log(error);
      });;
    });
  }

您应该正确定义变量...我更喜欢您应该了解es6语法,并对变量使用“ let”和“ const”,范围很广,谢谢:-@ ravi

In the promise you use an arrow function, but in the .size() line below you use an old style anonymous function, and then you lose your scope. 在promise中,您使用箭头函数,但是在下面的.size()行中,您使用旧样式的匿名函数,然后您失去了作用域。 You can try using arrow function for .size() 您可以尝试对.size()使用箭头功能

.size((error, value) => {})

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

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