-
-
Notifications
You must be signed in to change notification settings - Fork 229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
实现网络请求超时判断,超过三秒视为超时 #171
Comments
function loadImg(src){
new Promise((resolve,reject)=>{
let img = new Image()
img.onload=function(){
console.log("图片加载成功")
resolve(img)
}
img.error=function(){
reject(new Error(`Can not load ${src}`))
}
img.src=src
})
}
function timeout(){
return new Promise((reject)=>{
setTimeout(()=>{
reject("超时")
},3000)
})
}
//判断图片加载是否超时
Promise.race([loadImg,timeout])
.then((data)=>{
console.log(data)
}).catch(err=>{
console.log(err)
}) |
|
/**
* 请求超过4s自动失败
* @returns {Promise<Awaited<unknown>>}
*/
function getData () {
return Promise.race([
new Promise((resolve, reject) => {
// 模拟一个6s的请求
setTimeout(() => {
resolve('请求成功')
}, 6000)
}),
new Promise((resolve, reject) => {
setTimeout(() => {
reject('请求失败')
}, 4000)
})
]).then(res => {
console.log(res)
}, (error) => {
console.log(error)
})
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: