Search code examples
javascriptjqueryhtml2canvas

Get value of the pending Promise


I work on create PDF with pdfmake and i get images of many charts with html2canvas.
How i can get the value of the Promise of html2canvas return?

CODE

    var img = { token: html2canvas(document.getElementById("chartContainer")).then(canvas => {
    return canvas.toDataURL("image/jpeg,1.0")
    }).then(canvas =>{return canvas})}

    console.log (img.token); // Promise { <state>: "pending" }
    alert(img.token); // Object Promise

I want to use images outside the function. Thanks for your help!


Solution

  • You have to wait for the promise to complete. When the promise completes, the function you passed into .then(/*...*/) is called.

    You also don't need to use an additional .then after toDataURL, because toDataURL runs synchronously (it doesn't return a promise). You only need to use .then for functions that return a promise.

    So you can rewrite it like this instead:

    html2canvas(document.getElementById("chartContainer"))
        .then(canvas => {
            // This code will run once the promise has completed
            var img = { token: canvas.toDataURL("image/jpeg,1.0") };
            console.log(img.token);
            alert(img.token);
        });