I am creating a PDF with jsPDF. In the code I have some loops, where I create promises to add images to the document.
Now I want to add a new page in between the other promises if certain conditions are met. But the page is always added before every other promise. Here is my code:
var docPromises = [];
for (var i = 0; i < usedMonths.length; i++){
if(checkColumnPage(startPos)){
var addPagePromise = new Promise((resolve, reject) => {
doc.addPage();
resolve();
});
docPromises.push(addPagePromise);
}
var imgSourceMonth = eval("img_months_" + currentMonth);
(function(imgSrc, position) {
var clonedStartPos = position.slice();
var addImagePromiseMonth = calculateImageWidth(imgSrc, 20)
.then(function(width) {
doc.addImage(imgSrc, 'PNG', clonedStartPos[0], clonedStartPos[1], width, 20);
})
.catch(function(error) {
console.error(error);
});
docPromises.push(addImagePromiseMonth);
})(imgSourceMonth, startPos);
}
checkColumnPage(startPos)
returns true if a new page has to be added and false if not.
I resolve the promises like this:
Promise.all(docPromises)
The second part in the loop works perfectly. The order of the image is correct.
I logged every promise action to the console and it appeared that the page was always added first, followed by every other promise. I can't figure out the problem... In my mind it should work like this:
Iteration 1 (checkColumnPage = false): add image promise
Iteration 2 (checkColumnPage = false): add image promise
Iteration 3 (checkColumnPage = true): add page promise, add image promise
Iteration 4 (checkColumnPage = false): add image promise
...
But the page always comes first. Can anyone help me with this problem? Thanks in advance.
Promises are async and not guaranteed (or even expected) to resolve in order. In order to only call the next action after previous promise has resolved you have to chain them:
const promise = usedMonths.reduce((prevPromise, month) => {
return prevPromise.then(() => {
// do stuff
});
}, Promise.resolve());