[英]Promise called too early
当文件为JPG时,将在返回响应之前创建该文件(以在浏览器中显示调整大小的图片)。 但是,当它是PNG时,它将在写入PNG之前返回,从而导致Node.Js服务器崩溃,因为它无法为不存在的内容创建ReadStream:
调整器调用
else {
resizer
.resizeHandler(filepath, parsedUrl, fullDestinationPath)
.then(function () {
return self.send(response, 200, {'Content-Type': mime.lookup(fullDestinationPath)}, fs.createReadStream(fullDestinationPath));
});
}
调整大小
Resizer.prototype.resizeThenCrop = function(filepath, parsedUrl, fullDestinationPath){
return Jimp.read(filepath)
.then(function (picture) {
var cropWidth = parsedUrl.query.w,
cropHeight = parsedUrl.query.h;
calculate(picture, parsedUrl);
picture.resize(parseInt(parsedUrl.query.w), parseInt(parsedUrl.query.h))
.crop(parseInt((parsedUrl.query.w - cropWidth) / 2), parseInt((parsedUrl.query.h - cropHeight) / 2), parseInt(cropWidth), parseInt(cropHeight))
.quality(parseInt(parsedUrl.query.quality))
.write(fullDestinationPath)
})
.catch(function (err) {
console.error(err);
});
};
发送
Router.prototype.send = function (response, code, headers, data) {
response.statusCode = code;
if (headers) {
for (var index in headers) {
if (headers.hasOwnProperty(index)) {
response.setHeader(index, headers[index]);
}
}
}
if (data instanceof Stream) {
data.pipe(response);
} else {
response.end(data);
}
};
但是,也许它无法处理PNG,或者尝试调整其大小时出现错误? 我已经测试并确认不是简单的情况,只需将代码更改为此:
else {
resizer
.resizeHandler(filepath, parsedUrl, fullDestinationPath)
.then(function () {
//return self.send(response, 200, {'Content-Type': mime.lookup(fullDestinationPath)}, fs.createReadStream(fullDestinationPath));
});
}
现在它什么也不返回,并且我的浏览器将一直等待,因为它没有返回响应。 但是它确实像使用JPG一样在文件夹中创建文件,这意味着它确实起作用。 在实际创建调整大小的文件之前调用createReadStream时,由于该文件不存在,将导致崩溃。 该文件也不会创建,因为创建它的服务器已停止。 错误:
Error: ENOENT: no such file or directory, open '/var/www/pngbla_w512_h53_q80.png'
at Error (native)
我该怎么做才能使其对我的PNG正常工作? 而且为什么对我的PNG文件不起作用,即使对于某些JPG文件也要花费20秒,因为它已调整为高分辨率。
编辑:我已经尝试了多种大小,即使调整大小几乎是瞬间〜5ms,仍然会在使用PNG之前调用响应。
显然,它已经开始写JPG和仅在完成BMP时,我使用回调将代码更改为:
Resizer.prototype.resizeThenCrop = function(filepath, parsedUrl, fullDestinationPath){
return Jimp.read(filepath)
.then(function (picture) {
var cropWidth = parsedUrl.query.w,
cropHeight = parsedUrl.query.h;
calculate(picture, parsedUrl);
return new Promise(function(resolve, reject) {
picture.resize(parseInt(parsedUrl.query.w), parseInt(parsedUrl.query.h))
.crop(parseInt((parsedUrl.query.w - cropWidth) / 2), parseInt((parsedUrl.query.h - cropHeight) / 2), parseInt(cropWidth), parseInt(cropHeight))
.quality(parseInt(parsedUrl.query.quality))
.write(fullDestinationPath, function(err) {
if(err) {
return reject(err);
}
return resolve(fullDestinationPath);
});
});
})
.catch(function (err) {
console.error(err);
});
};
问题是picture.resize没有返回承诺,因此它继续运行而无需等待.write完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.