How can I call a function after all promises have been resolved? I have an HTML document with three tables. Using html2canvas(), I create a JPG by iterating over them in a forEach() loop:
JavaScript
var elements = document.querySelectorAll( 'table' );
elements = Array.from( elements );
var zip = new JSZip(),
img = '';
elements.forEach( function( element ) {
html2canvas( element ).then( canvas => {
var styleID = element.getAttribute('id');
img = new Image();
img.src = canvas.toDataURL( 'image/jpeg' );
document.body.appendChild( img );
zip.file( styleID + '.jpg', img.src );
}).then( generateZip );
});
function generateZip () {
// Generate the zip file asynchronously
zip.generateAsync({type:'blob'}).then( function( content ) {
saveAs( content, 'archive.zip' );
});
}
The problem is generateZip() gets called three times, once for each loop. How can I call generateZip() just one time, after all promises have been resolved, to create a single zip file?