Search code examples
javascriptjquerypromiseinternet-explorer-11jszip

JSZip load multiple files with Promise.all in IE11


We are developing a tool for users to upload zip packages to an intranet site at our company. We are using jszip to check inside the zip files and be sure the meet with certain policy and format guidelines.

We look for certain files inside the zip and there may be 0 to 3 xml files we are specifically interested in. We then want to expand those files and check some of their contents once they are all loaded.

I followed this suggestion for how to do that:

var zip = JSZipObject...

var promises = [];
var fileList = [file0,file1...fileX];

fileList.forEach(function(file){
    promises.push(zip.file(file.name).async('string'));
});

return Promise.all(promises);

And this works great in Chrome, but in IE there is no native Promise support.

Unfortunately most of our company is still using IE11, so I need to come up with a solution that will work in both Chrome and IE11.

I am familiar with the jQuery versions of promises and have used a similar trick with them to wait until all have been resolved.

return $.when.apply(null,[promises]);

But that doesn't seem to work because the promises returned by zip.file().async() aren't jQuery promises.

Is there a way that I can wrap the JSZip promises in jQuery or some other way that I can deal with this?


Solution

  • You could convert the jszip promises to jQuery promises using something like this (I haven't tested it, but you get the idea):

    function promiseToDeferred(p) {
      var dfd = jQuery.Deferred()
    
      p
        .then(function(x) { dfd.resolve(x) })
        .catch(function(err) { dfd.reject(err) })
    
      return dfd.promise()
    }
    

    So your bit of code would look something like:

    var fileList = [file0,file1...fileX]
    
    var promises = fileList
      .map(function(file) { return zip.file(file.name).async('string') })
      .map(promiseToDeferred)
    
    return jQuery.when.apply(null,[promises])