I asked this before and tried to change it based on some answers but still have an issue with the promises.
This is actually multiple promises but the main issue is that I am calling pouch.get to get a list of images. I then go through a for/loop to create some markup (which works fine if I don't have the resize promise code). I am trying to create a bunch of thumbnail images to show on a phone in a grid.
I made the resize code a promise to try and get the resize to finish before going and getting another image to resize. But it ends up only doing one onload event for the last image and that is all that shows.
What is happening is that for each loop it goes into the resize, sets the onload event, copies the url to the image then jumps out and does the next loop and the onload event doesn't get fired until the last loop (image), which displays on the screen.
My resize Promise:
function resizeImageToImgPromise(showImage, maxWidth, maxHeight, url) {
// Set img src to ObjectURL
return new Promise(function (resolve, reject) {
var test;
test = 'test';
showImage.onload = function () {
URL.revokeObjectURL(this.src);
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
... removed code to make it easier to read and not germane to the issue
showImage.src = canvas.toDataURL("image/png");
showImage.width = width;
showImage.height;
showImage.style.display = "inline";
showImage.style.margin = "10px"
resolve();
}
showImage.src = url;
})
}
Here is the promise that calls this in a for loop:
function readAllImagesFromPouch(id, imageDisplay) {
return new Promise(function (resolve, reject) {
var startElement = document.getElementById(imageDisplay);
var image = "";
var imgBlob;
var base64str;
// Get all attachments for this id
DB_TaskImages.get(id, { attachments: true }).then(function (doc) {
for (var key in doc._attachments) {
var img = document.createElement('img');
base64str = doc._attachments[key].data;
blobUtil.base64StringToBlob(base64str).then(function (myBlob) {
console.log();
return blobUtil.createObjectURL(myBlob);
}).then(function (myUrl) {
img.src = myUrl;
resizeImageToImgPromise(img, "100", "60", myUrl).then(function () {
$(startElement).append(img.outerHTML); return;
}).catch(function () { // this is the catch for the resize
alert("this is an error");
})
}).catch(function (err) { // this is the catch for the blobUtil
// error
});
}
return;
}).then(function () {
resolve();
}).catch(function (err) { // this is the catch for the DB_TaskImages.get
reject(err);
})
}); // end of promise
}
And this is originally called from:
readAllImagesFromPouch("006", "divImages").then(function () {
}).catch(function (err) {
console.log("In catch for readAllImagesFromPouch with err: " + err);
})