[英]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.