I want to call UseScreenshots after my two html2canvas have been called.
function Main()
{
var screenshot1, screenshot2;
html2canvas($('#div1'),
{
onrendered: function (canvas)
{
screenshot1 = canvas.toDataURL('image/png');
}
});
html2canvas($('#div2'),
{
onrendered: function (canvas)
{
screenshot2 = canvas.toDataURL('image/png');
}
});
UseScreenshots(screenshot1, screenshot2);
}
In the example above screenshot1 and screenshot2 will still be undefined when calling UseScreenshots.
Following deceze's answer, I'll use Promise.all:
Promise.all(
[
new Promise(function (resolve)
{
html2canvas($('#div1'),
{
onrendered: function (canvas)
{
resolve(canvas.toDataURL('image/png'));
}
});
},
new Promise(function (resolve)
{
html2canvas($('#div2'),
{
onrendered: function (canvas)
{
resolve(canvas.toDataURL('image/png'));
}
});
}
]).then(function (screenshots)
{
UseScreenshots(screenshots[0], screenshots[1]);
});
Promises can solve exactly this case very elegantly:
Promise.all([new Promise(Function1), new Promise(Function2)]).then(Function3);
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all.
You'll need to adapt Function1 and Function2 to use promises correctly, or perhaps even to return promises themselves, or wrap them appropriately.
Sample to create one promise:
new Promise(function (resolve) {
html2canvas($('#div1'), {
onrendered: function (canvas) {
resolve(canvas.toDataURL('image/png'));
}
});
})
You'll receive the resolved values as an array in your .then callback:
Promise.all([..]).then(function (screens) { UseScreenshots(screens[0], screens[1]); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With