两个异步函数后回调

时间:2016-01-20 11:16:30

标签: javascript asynchronous callback

我想在调用两个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);
}

在上面的示例中,screenshot1screenshot2在调用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]);
});

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 您需要调整Function1Function2以正确使用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]); });