我有一些代码可以返回http请求的结果,如果5秒钟内未返回请求,则返回错误:
const doRequest = () => request('http://www.google.com');
const doTimeout = () => new Promise((resolve, reject) => setTimeout(() => reject(new Error(`Request timeout)), 5000));
return Promise.race([
doRequest,
doTimeout,
]);
在这种情况下,如果请求在5秒以下返回,则doTimeout
继续运行,直到5秒后自然超时。取消剩余的承诺是个好主意吗?例如,
const doRequest = () => request('http://www.google.com');
let timeout;
const doTimeout = () => new Promise((resolve, reject) => {
timeout = setTimeout(() => reject(new Error(`Request timeout)), 5000);
});
const requestPromise = doRequest();
return Promise.race([
requestPromise,
doTimeout,
])
.then(response => {
clearTimeout(timeout);
requestPromise.cancel();
return response;
})
.catch(err => {
clearTimeout(timeout);
requestPromise.cancel();
throw err;
});