gpt4 book ai didi

javascript - 将 Promise 用于 onload 和 onerror 后返回状态值

转载 作者:行者123 更新时间:2023-12-05 04:59:31 25 4
gpt4 key购买 nike

我正在尝试使用 javascript onload 和 onerror 查看页面/img 是否成功加载。我正在尝试读取状态变量,但是当我分配变量以读取状态时无法这样做。我正在尝试使用提供的可能答案中概述的 promise ,但仍然有些困惑。


const validateInput = (input) => {
const errors = {};
...

if(!(isImgURlValid(input)))
{
errors = `wrong image'`
}
...
return errors;

const isImgURlValid = (path) => {
let img = document.createElement('img');
img.src = path;
let valid
const promise = new Promise(resolve => {
const img = new Image();
img.onload = () => resolve({path, "status": 'ok'});
img.onerror = () => resolve({path, "status": 'error'});
img.src = path;
});
promise.then(function(val) {
console.log(val);
valid = val.status
});
console.log (valid)
}

//when I use async, my render functions no long render the errors properly
export const renderImgUrlInput = ({ input, label, type, size, required, meta: { touched, error } }) => (
<div className={
cs('form-group', size, {
'has-error': touched && error,
'required-input' : required
})
}>
<label className="control-label" htmlFor={input.name}>{label}</label>
<input {...input} placeholder={required ? 'Required' : ''} className="form-control" />
{touched && error &&
<span className="help-block">{error}</span>
}
{touched && !error &&
<h1 className="help-block">{error} 'Image worked'</h1>
}
</div>
)

最佳答案

const isImgURLValid = (path) => {
return new Promise((resolve, reject) => {
const img = document.createElement("img");
img.src = path;
img.onload = resolve;
img.onerror = reject;
img.src = path;
document.body.appendChild(img);
});
};

isImgURLValid("https://www.gravatar.com/avatar/206601a888686677c4a74c89d9a2920f?s=48&d=identicon&r=PG")
.then(() => console.log("Path is valid"))
.catch(() => console.error("Path isn't valid"))

关于javascript - 将 Promise 用于 onload 和 onerror 后返回状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63472275/

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