Domanda

I want to create a PDF document with multiple images. Since they get loaded form a webserver, I do this asynchronously. When all images are loaded and added to the document, I want to display the result.

// create a new document
var doc = new jsPDF();

var count = 0;
for (var i = 0; i < urls.length; ++i) {
    // load image from url and add to document
    // internally, waits for img.onload()
    image(urls[i], function(e) {
        // don't care about the coordinates,
        // I simplified this for this example
        doc.addImage(e.data, 'jpeg', 0, 0, 10, 10);
        // increase counter of finished callbacks
        count++;
    });
}

// wait for all callbacks to finish
while (count < urls.length);

// output the resulting document
doc.output('dataurl');

When I run this code, the browser window freezes for some seconds and then stops execution of the script. It seems like the while loop doesn't finish.

What's wrong with my code? I think there must be a way to synchronize your code at some points in JavaScript. How is this done commonly?

È stato utile?

Soluzione

Thank you Ian, for pointing me towards promises. Since I already make use of jQuery, I decided to use their implementation. The image() function for loading returns a promise now and this is what I ended up with.

// create a new document
var doc = new jsPDF();

// load all images and give me the promises
var promises = urls.map(image);

// handle individual results
promises.map(function(promise) {
    promise.done(function(e) {
        // don't care about the coordinates,
        // I simplified this for this example
        doc.addImage(e.data, 'jpeg', 0, 0, 10, 10);
    }).fail(console.log);
});

// handle overall readiness
$.when.apply($, promises).done(function() {
    // output the resulting document
    doc.output('dataurl');
}, console.log);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top