繁体   English   中英

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

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

我已经在下面编写了函数。 我需要读取图像的尺寸,然后将其缩小。 初始回调后,我想使用计算出的widthheight值来调整大小和保存图像。 我的变量不在范围内,但出现了ReferenceError: width is not defined 如何正确确定这些变量的范围,以便它们可用于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

在promise中,您使用箭头函数,但是在下面的.size()行中,您使用旧样式的匿名函数,然后您失去了作用域。 您可以尝试对.size()使用箭头功能

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

暂无
暂无

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

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