Skip to content
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

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments
Open

实现网络请求超时判断,超过三秒视为超时 #171

Sunny-117 opened this issue Nov 3, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@Coloey
Copy link

Coloey commented Nov 22, 2022

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)
})

@hyxieshi
Copy link

// promise.race() 只要有一个promise 出错就报错
      function delay(time) {
        return new Promise((res, rej) => {
          setTimeout(() => {
            rej("超时");
          }, time * 1000);
        });
      }
      Promise.race([delay(3), requestData(url, "get")])
        .then((res) => {
          console.log("cg", res);
        })
        .catch((err) => {
          console.log("sb", err);
        });

@topulikeweb
Copy link

/**
 * 请求超过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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants