-
-
Notifications
You must be signed in to change notification settings - Fork 241
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
Comments
const abort = new AbortController();
let res = null;
fetch(url, {
signal: abort.signal
}).then(_res => {
res = _res;
})
setTimeout(() => {
if (!res) abort.abort();
}, 5000); |
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)
}) |
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)
})
|
function requestAbort() { function request(t) { function requestWrap(fn) { requestWrap(request)(6000).then((data) => { |
function request(url,maxTime){
return new Promise((resolve,reject) => {
const controller = new AbortController()
fetch(url,{signal:controller.signal}).then(res => {
resolve(res)
})
setTimeout(() => {
controller.abort()
reject(new Error('超时了'))
},maxTime)
})
} |
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: