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

请求5s未完成就终止 #160

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

请求5s未完成就终止 #160

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

Comments

@Sunny-117
Copy link
Owner

No description provided.

@fencer-yd
Copy link

const abort = new AbortController();
let res = null;
fetch(url, {
  signal: abort.signal
}).then(_res => {
  res = _res;
})

setTimeout(() => {
  if (!res) abort.abort();
}, 5000);

@Allure-eve
Copy link

const funWait = (call, timeout = 5000) => {
  let wait = new Promise((resolve, reject) => {
    setTimeout(() => {
      reject('请求超时')
    }, timeout)
  })
  return Promise.race([call(), wait])
}
const t = () => new Promise(resolve => setTimeout(resolve, 4000))
const t2 = () => new Promise(resolve => setTimeout(resolve, 6000))
funWait(t).then(res => {
  console.log("t1 resolve")
}).catch(err => {
  console.log("t1 timeout")
})
funWait(t2).then(res => {
  console.log("t2 resolve")
}).catch(err => {
  console.log("t2 timeout", err)
})

@xianjianlf2
Copy link

const abortPromise = (promise, timeout) => {
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => {
            reject('abort promise')
        }, timeout)
        promise
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
            .finally(() => {
                clearTimeout(timer)
            })
    })
}

// test case
const promiseA = new Promise((resolve) => {
    setTimeout(() => {
        resolve('success')
    }, 6000)
})
abortPromise(promiseA, 5000)
    .then((res) => {
        console.log(res)
    })
    .catch((err) => {
        console.log(err)
    })

@Windseek
Copy link

Windseek commented Apr 7, 2024

function requestAbort() {
return new Promise((rs, rj) => {
setTimeout(
() => rj('请求失败')
, 5000);
})
}

function request(t) {
return new Promise((rs, rj) => {
setTimeout(
() => rs('请求成功')
, t);
})
}

function requestWrap(fn) {
return function(...args) {
return Promise.race([requestAbort() , fn(...args)]);
}
}

requestWrap(request)(6000).then((data) => {
console.log(data);
});

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

5 participants