【发布时间】:2019-09-10 14:55:53
【问题描述】:
我已经阅读了关于这个主题的几个问题,但我仍然看不出有什么问题。我有两个函数,一个从文件初始化图像并读取其尺寸,将它们设置为对象的变量。第二个检查尺寸是否在限制范围内。
功能:
checkDimensions: function() {
console.log('entering chekDimensions');
if (options.maxDimensionsWH > 0) {
console.log(this.checkWidth);
console.log(this.checkHeight);
if ((this.checkWidth <= options.maxDimensionsWH || this.checkHeight <= options.maxDimensionsWH)
&& (this.checkWidth > 0 && this.checkHeight > 0)) {
console.log('returning true');
return true;
} else {
console.log('returning false');
return false;
}
} else {
return true;
}
},
initializeCheckImage: function(file) {
console.log('entering initialization');
var d = $.Deferred();
var reader = new FileReader();
reader.onload = function (e) {
var img = new Image;
img.onload = function() {
this.checkWidth = img.width;
this.checkHeight = img.height;
console.log('initializing the image');
console.log(this.checkWidth);
console.log(this.checkHeight);
d.resolve();
};
console.log('assigning reader.result');
img.src = reader.result;
};
console.log('assigning a file to the reader');
reader.readAsDataURL(file);
console.log('returning deferred');
return d.promise();
}
以及它们的名称:
this.initializeCheckImage(file).done(check = this.checkDimensions());
从控制台可以清楚地看到,第二个函数的执行发生在调用d.resolve(); 之前。
> 21:13:34.460 entering initialization
> 21:13:34.461 assigning a file to the reader
> 21:13:34.462 returning deferred
> 21:13:34.462 entering chekDimensions
> 21:13:34.462 0
> 21:13:34.463 0
> 21:13:34.463 chekDimensions returning false
> 21:13:34.478 assigning reader.result
> 21:13:34.493 initializing the image
> 21:13:34.494 30
> 21:13:34.494 30
我做错了什么?谢谢!
【问题讨论】:
-
.done(check = this.checkDimensions());您正在立即调用checkDimensions,将其返回值分配给check,并将该返回值作为Promise 回调传递给done