[英]Callback after two asynchronous functions
I want to call UseScreenshots
after my two html2canvas
have been called. 我要在调用两个
html2canvas
之后调用UseScreenshots
。
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
. 在上面的示例中,调用
UseScreenshots
时, screenshot1
和screenshot2
仍将是undefined
。
Following deceze 's answer, I'll use Promise.all : 按照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]);
});
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 . 请参阅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. 您将需要修改
Function1
和Function2
来正确使用promise,或者甚至自己返回promise,或适当地包装它们。
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: 您将在
.then
回调中将解析的值作为数组接收:
Promise.all([..]).then(function (screens) { UseScreenshots(screens[0], screens[1]); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.