Is there a way to chain promises by iterating through an array?
For example, I'm trying to convert the content of multiple tabs into their own separate pdf pages using jsPDF and html2canvas.
const pdf = new jsPDF('l');
let index = 1;
let input = document.getElementById('print');
const formatPage = (canvas) => {
const imgData = canvas.toDataURL('image/jpg');
pdf.addImage(imgData, 'JPEG', 10, 10, 200, 100, '', 'FAST', 0);
}
const nextPage = () => {
pdf.addPage();
document.getElementById(`${tabs[index]}`).click();
index++;
input = document.getElementById('print');
}
html2canvas(input)
.then(canvas => {
formatPage(canvas);
nextPage();
return html2canvas(input);
})
.then(canvas => {
formatPage(canvas);
nextPage();
return html2canvas(input);
})
.then(canvas => {
formatPage(canvas);
pdf.save('download.pdf');
})
Is there a way to do the same thing through iteration of the tabs array? I want to be able to chain a dynamic number of promises instead of hard coding it because for example, every page might not have the same number of tabs.
Solution:
I couldn't get it to work with Promise.all() but this is how I did it.
async generatePages() {
for(let index = 0; index !== tabs.length; index++) {
document.getElementById(`${tabs[index]}`).click();
input = document.getElementById('print');
await this.processPage(input, index, tabs.length - 1);
}
}
processPage(input, index, end) {
const formatPage = (canvas) => {
const imgData = canvas.toDataURL('image/jpg');
pdf.addImage(imgData, 'JPEG', 10, 10, 200, 100, '', 'FAST', 0);
}
return html2canvas(input).then(canvas => {
formatPage(canvas);
if(index !== end) {
pdf.addPage();
} else {
pdf.save('download.pdf');
}
})
}