Search code examples
javascriptjquerypromisehtml2canvas

make .each() wait for converting element to DataURL


I am using html2canvas for converting html2canvas,

I'm parsing html using .each and then pass elements to html2canvas. after element converted to DataURL. I push it to an array content.

$('.itinerary-section-detail').each(function( index, element ) { 
                 setTimeout(function() {
                   console.log(element);
                       html2canvas(element).then(function(canvas) {
                            element.appendChild(canvas);
                             elem  = canvas.toDataURL();
                              var item = {};
                              item["image"] = elem;
                              item["width"] = 595;
                              content.push(item);
                          }); 
                  }, 4000);
            });

but the issue is that time varies to convert an element to DataURL. that's why the order of elements are randomize. So I need to wait until an element get converted to DataURL, push it into content array and then comes next element from .each.

Please suggest me a way here. Tried setTimeout, didn't work.


Solution

  • You can't just loop over asynchronous elements, because they don't pause loop. Instead you can construct array of promises and use $.when. Then a callback you provide will be called once all promises resolve:

    var promises = $('.itinerary-section-detail').map(function(index, element) {
      console.log(element)
      return html2canvas(element).then(function(canvas) {
          element.appendChild(canvas)
          var elem = canvas.toDataURL()
    
          return {
            image: elem,
            width: 595
          }
        })
    }).get()
    
    $.when.apply(null, promises).then(function() {
      var content = [].slice.call(arguments)
      console.log(content)
    })