首页 > 解决方案 > 如何将变量分配给回调?

问题描述

我有这个函数,它需要一个 URL 和回调:

function getMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { return callback(this.width, this.height); }
}

这个回调函数是这样调用的:(这有效并警告正确的输出前 100px , 100px)

    getMeta(
        i_url, //This being the URL (in base64 or real web url)
        function(width, height) { alert(width + 'px ' + height + 'px') }
      );

但是,每当我尝试为其分配一个变量并切换返回警报时,我都会得到未定义的..

    const test = getMeta(
        i_url,
        function(width, height) { return width + 'px ' + height + 'px' }
      );
    alert(test);

警报消息:未定义

标签: javascriptcallback

解决方案


您没有在getMeta方法内返回任何值,您只从回调中返回,该回调永远不会从对方法的原始调用中传递出来getMeta

按照这个代码,看看你是否明白

function getMeta(url, callback) {
    var img = new Image();
    img.src = url;
    /*
        This return is only assigned to img.onload
        But this assignment does not make any sense. 
    */
    // img.onload = function() { return callback(this.width, this.height); }
    /* if you want to use the image height and width inside your own logic you can include that logic in the callback */
    img.onload = function() { callback(this.width, this.height) }
    // maybe you can return the IMG from this method
    return img;
}

您可以声明一个全局对象并从回调中引用宽度和高度

let imageMeta = {height: null, width: null}
getMeta(
    i_url,
    function(width, height) { imageMeta.width = width; imageMeta.height = height }
);

如果您想要一个更强大的解决方案,您应该研究Promise


推荐阅读