如何将变量分配给回调?
How to assign a variable to a callback?
我有这个函数接受 URL 和回调:
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { return callback(this.width, this.height); }
}
这个回调函数是这样调用的:(这有效并提醒正确的输出e.x。100px,100px)
getMeta(
i_url, //This being the URL (in base64 or real web url)
function(width, height) { alert(width + 'px ' + height + 'px') }
);
然而,每当我尝试为它分配一个变量,并关闭 return 的警报时,我得到未定义的..
const test = getMeta(
i_url,
function(width, height) { return width + 'px ' + height + 'px' }
);
alert(test);
警报消息:未定义
您没有 return 在 getMeta
方法中输入任何值,您只是 return 来自从未从原始调用传递给 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 }
);
如果您想要更强大的解决方案,您应该查看 promises
我有这个函数接受 URL 和回调:
function getMeta(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { return callback(this.width, this.height); }
}
这个回调函数是这样调用的:(这有效并提醒正确的输出e.x。100px,100px)
getMeta(
i_url, //This being the URL (in base64 or real web url)
function(width, height) { alert(width + 'px ' + height + 'px') }
);
然而,每当我尝试为它分配一个变量,并关闭 return 的警报时,我得到未定义的..
const test = getMeta(
i_url,
function(width, height) { return width + 'px ' + height + 'px' }
);
alert(test);
警报消息:未定义
您没有 return 在 getMeta
方法中输入任何值,您只是 return 来自从未从原始调用传递给 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 }
);
如果您想要更强大的解决方案,您应该查看 promises