javascript - Promise Race 中的 setTimeout 立即捕获
问题描述
我有 2 个 promise, afetch
和 a 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);
})
]);
推荐阅读
- c++ - 如何处理模板 const 和非 const 参数?
- saml - 在 SAML 响应 XML 中生成签名值的步骤
- swift - 如何在 SwiftUI 中使用 @State 和 fullScreenCover 在视图之间切换
- python - 使用 PySimpleGUI,如何让它下载带有进度条的文件?
- javascript - 异步与同步流以及如何确保排序
- visual-studio - Visual Studio 测试资源管理器图标
- c++ - 什么时候可以在头文件中定义函数?
- r - 用括号括住以 sd 结尾的变量
- php - 如何使用 Laravel 向动态手机发送通知?
- c++ - 为什么linux ld somtime使用libs的符号链接