Promise Race 中的 setTimeout 立即捕获
setTimeout inside Promise Race immediately catch
我有 2 个承诺,一个 fetch
和一个 setTimeout
,fetch 等待 5 秒,setTimeout 等待 4 秒。
我不知道为什么,但 setTimeout 立即触发!
myService( args )
.then( result => {
console.log(result);
})
.catch( timeoutError => { // <----------------- FIRE IMMEDIATELY
console.error(timeoutError);
})
;
function myService( args ){
return Promise.race([
fetch("http://localhost/wait-ten-seconds"),
new Promise( (_, timeexpired) => {
return setTimeout( function() {
console.log("timeout");
timeexpired({msg: "call timeout", code: 100, data: null});
}
, 4000)
})
]);
}
我是这样解决的:
我创建了一个模拟超时的函数
let activeTimer = null;
let checkTimer = (startTimer, timeExpired) => {
activeTimer = setTimeout(() => {
if( (new Date()).getTime() - startTimer < TIMEOUT_DURATION_MS ) checkTimer(startTimer, timeExpired);
else timeExpired( errorMessage.TIMEOUT_EXPIRED );
}, 1000);
};
Promise.race([
new Promise( (httpResponse, httpError) => {
return fetch(url)
.then(response => {
clearTimeout( activeTimer );
activeTimer = null;
httpResponse( response );
})
.catch( error => {
httpError( error );
})
})
,
new Promise( (_, timeExpired) => {
checkTimer((new Date()).getTime(), timeExpired);
})
]);
我有 2 个承诺,一个 fetch
和一个 setTimeout
,fetch 等待 5 秒,setTimeout 等待 4 秒。
我不知道为什么,但 setTimeout 立即触发!
myService( args )
.then( result => {
console.log(result);
})
.catch( timeoutError => { // <----------------- FIRE IMMEDIATELY
console.error(timeoutError);
})
;
function myService( args ){
return Promise.race([
fetch("http://localhost/wait-ten-seconds"),
new Promise( (_, timeexpired) => {
return setTimeout( function() {
console.log("timeout");
timeexpired({msg: "call timeout", code: 100, data: null});
}
, 4000)
})
]);
}
我是这样解决的:
我创建了一个模拟超时的函数
let activeTimer = null;
let checkTimer = (startTimer, timeExpired) => {
activeTimer = setTimeout(() => {
if( (new Date()).getTime() - startTimer < TIMEOUT_DURATION_MS ) checkTimer(startTimer, timeExpired);
else timeExpired( errorMessage.TIMEOUT_EXPIRED );
}, 1000);
};
Promise.race([
new Promise( (httpResponse, httpError) => {
return fetch(url)
.then(response => {
clearTimeout( activeTimer );
activeTimer = null;
httpResponse( response );
})
.catch( error => {
httpError( error );
})
})
,
new Promise( (_, timeExpired) => {
checkTimer((new Date()).getTime(), timeExpired);
})
]);