gpt4 book ai didi

javascript - 子函数完成后如何从父函数返回值

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:06:04 25 4
gpt4 key购买 nike

我正在实现一个简单的验证函数,它应该根据图像大小返回 true/false。内部 img.onload 函数需要一些时间来执行,因此父 checkImagesWidth 应该等待它完成。

代码如下:

checkImagesWidth: function (file, restrictions) {
var img = new Image()
img.src = window.URL.createObjectURL(file)
img.onload = () => {
window.URL.revokeObjectURL(img.src)
return (img.naturalWidth >= restrictions.width) || (img.naturalHeight >= restrictions.height)
}
}

换句话说,这个想法是在 checkImagesWidth() 之后得到 true/false 并像常规一样在 if 语句中使用这个值true/false 值。

我试图通过回调、 promise 、异步/等待来实现这种方法,但没有成功。这可能吗?

最佳答案

onload 是仅在加载图像时才会执行的事件,因此 checkImagesWidth 将在 onload 执行之前执行并退出。如果您能解释为什么需要 true/false 返回会更好,这将有助于正确构建它。

这里有几种方法可以做你想做的事

首先是回调函数

function callback(boolValue) {
// do something with it
}

checkImagesWidth: function (file, restrictions, callback) {
var img = new Image()
img.src = window.URL.createObjectURL(file)
img.onload = () => {
window.URL.revokeObjectURL(img.src)
callback(img.naturalWidth >= restrictions.width) || (img.naturalHeight >= restrictions.height)
}
}

第二个可能是 promise

checkImagesWidth: function (file, restrictions, callback) {
return new Promise(function(resolve, reject) {
var img = new Image()
img.src = window.URL.createObjectURL(file)
img.onload = () => {
window.URL.revokeObjectURL(img.src)
if((img.naturalWidth >= restrictions.width) || (img.naturalHeight >= restrictions.height)){
resolve(true)
}else {
reject(false)
}
}
});
}

consumer: function() {
checkImagesWidth().then(()=>{
// when it true do something
}).catch(()=>{
//false case
})

}

关于javascript - 子函数完成后如何从父函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57574671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com