Skip to content Skip to sidebar Skip to footer

Return A Promise Result In Order Using The Library Dom-to-image

Using the dom-to-image library we can convert an image using Promises. Usage example, conversion from DOM object to PNG image: var node = document.getElementById('my-node'); domto

Solution 1:

Using async/await:

HTML:

<divclass="page">Hello 1</div><divclass="page">Hello 2</div><divclass="page">Hello 3</div><divclass="page">Hello 4</div>

JS (JSFiddle Link):

let pages = document.querySelectorAll('.page');

asyncfunctiongetPageUrls() {
    for (let page of pages) {
        const url = awaitconvertToPng(page);
        console.log(url);
    }
}

asyncfunctionconvertToPng(page) {
    returnawait domtoimage.toPng(page);
}

getPageUrls();

Based off OPs sample (JSFiddle):

let pages = document.querySelectorAll('.page');

for (let page of pages) {
    convertToPng(page);
}

asyncfunctionconvertToPng(page) {
    const dataUrl = await domtoimage.toPng(page);
    console.log(dataUrl);
}

getPageUrls();

With this solution code execution is stopped until convertToPng yields a result at each iteration.

Solution 2:

As I understand for this case you can use Promise.all. Smthing like this one:

let pages = document.querySelectorAll('.page');

Promise.all(Array.prototype.slice.call(pages,0)
.map(page =>domtoimage.toPng(page)
).then((pages)=>{.... your handler....});

More information about Promise.all you can get from MDN

Solution 3:

The easiest way to chain the promises so they run in sequence is using Array#reduce

pages.reduce((promise, page) => 
    promise.then(() =>convertToPng(page.firstElementChild)),
    Promise.resolve() // this starts the chain
);

This will, as you stated in the comment wait until page1 is complete, before beginning with the next page

Though, I get the feeling it's only the output order that is important, in which case the answer by @VasylMoskalov is more appropriate

As @Keith pointed out in a comment - convertToPng does not return anything (let alone a promise)

functionconvertToPng(page) {
//vvvvvv important you return the promise herereturn domtoimage.toPng(page)
    .then(function (dataUrl) {
      console.log(page); // prints pages randomly (e.g. page3, page1, page2) 
    })
}

Post a Comment for "Return A Promise Result In Order Using The Library Dom-to-image"