I am making a node.js application that can create thumbnails for images. To avoid freezing the application while generating thumbnails I decided to use an asynchronous library for creating thumbnails. However depending on the image multiple thumbnail sizes might be needed.
var thumbnailSizes = [100];
if (image.type == 'coolImage') thumbnailSizes.push(500);
generateThumbnails(image.filename, thumbnailSizes).then(function() {
// Do cool things with the saved thumbnails (This is never reached)
});
function generateThumbnails(filename, thumbnailSizes) {
return new Promise(resolve => {
var path = filename.substring(0, filename.lastIndexOf('\\'));
console.log('start');
console.log('length = ' + thumbnailSizes.length);
thumb({
prefix: thumbnailSizes[0] + '_';
source: filename,
destination: path,
width: thumbnailSizes[0]
}).then(function () {
if (thumbnailSizes.length > 1) {
console.log('next');
generateThumbnails(filename, thumbnailSizes.splice(0, 1));
} else {
console.log('finished');
resolve('true');
}
}).catch(function (e) {
console.log('error');
});
console.log('end');
});
}
This code successfully creates the first thumbnail but not the second. This is what my console looks like after the code stops running.
> Console Output
start
length = 2
end
next
start
length = 1
end
The code calls generateThumbnails()
for a second time successfully but does not call the thumb function again, skipping to the end and never resolving. How can I make this work?