为什么我的回调函数被调用了?

时间:2013-04-12 11:48:36

标签: javascript asynchronous callback

此刻我真的很难受,请看下面的代码:

var getImageFromUrl = function(url, callback) {
var img = new Image, data, ret={data: null, pending: true};

img.onError = function() {
    throw new Error('Cannot load image: "'+url+'"');
}
img.onload = function() {
    var canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext('2d');
    ctx.clearRect( 0, 0, canvas.width, canvas.height );
    ctx.drawImage(img, 0, 0);
    // Grab the image as a jpeg encoded in base64, but only the data
    data = canvas.toDataURL('image/jpeg').slice('data:image/jpeg;base64,'.length);
    // Convert the data to binary form
    data = atob(data)
    document.body.removeChild(canvas);

    ret['data'] = data;
    ret['pending'] = false;
    if (typeof callback === 'function') {
        callback(data);
    }
}
img.src = url;

return ret;
}

这是我对它的呼唤:

getImageFromUrl('pdfconversion/roundel.jpg', addImage);

所以基本上,对于我的方法来做我真正想要它做的事情(这里没有显示)我需要回调函数,在这种情况下是在访问getImageFromUrl方法后立即调用的'addImage'。此时,调用getImageFromUrl方法,然后在最终调用'addImage'的回调函数之前运行我的其余代码(上面未显示)。如何让这个成为下一个电话?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

删除回调并按顺序调用它:

getImageFromUrl('pdfconversion/roundel.jpg');
addImage();