我想在调用两个UseScreenshots
后致电html2canvas
。
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);
}
在上面的示例中,screenshot1
和screenshot2
在调用undefined
时仍为UseScreenshots
。
按照 deceze 的回答,我会使用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]);
});
答案 0 :(得分:5)
Promise可以非常优雅地解决这个问题:
Promise.all([new Promise(Function1), new Promise(Function2)]).then(Function3);
请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
您需要调整Function1
和Function2
以正确使用promise,或者甚至可以自己返回promise,或者适当地包装它们。
创建一个承诺的示例:
new Promise(function (resolve) {
html2canvas($('#div1'), {
onrendered: function (canvas) {
resolve(canvas.toDataURL('image/png'));
}
});
})
您将在.then
回调中收到已解析的值数组:
Promise.all([..]).then(function (screens) { UseScreenshots(screens[0], screens[1]); });