异步/等待超时 [英] Timeout in async/await
问题描述
我正在使用Node.js和TypeScript,并且正在使用async/await
.
这是我的测试用例:
I'm with Node.js and TypeScript and I'm using async/await
.
This is my test case:
async function doSomethingInSeries() {
const res1 = await callApi();
const res2 = await persistInDB(res1);
const res3 = await doHeavyComputation(res1);
return 'simle';
}
我想为整个功能设置一个超时时间. IE.如果res1
花费2秒,res2
花费0.5秒,res3
花费5秒,我想超时,在3秒后让我抛出错误.
I'd like to set a timeout for the overall function. I.e. if res1
takes 2 seconds, res2
takes 0.5 seconds, res3
takes 5 seconds I'd like to have a timeout that after 3 seconds let me throw an error.
正常调用setTimeout
会出现问题,因为范围丢失了:
With a normal setTimeout
call is a problem because the scope is lost:
async function doSomethingInSeries() {
const timerId = setTimeout(function() {
throw new Error('timeout');
});
const res1 = await callApi();
const res2 = await persistInDB(res1);
const res3 = await doHeavyComputation(res1);
clearTimeout(timerId);
return 'simle';
}
我无法用普通的Promise.catch
来捕捉它:
And I cannot catch it with normal Promise.catch
:
doSomethingInSeries().catch(function(err) {
// errors in res1, res2, res3 will be catched here
// but the setTimeout thing is not!!
});
关于如何解决的任何想法?
Any ideas on how to resolve?
推荐答案
You can use Promise.race
to make a timeout:
Promise.race([
doSomethingInSeries(),
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 11.5e3))
]).catch(function(err) {
// errors in res1, res2, res3 and the timeout will be caught here
})
如果没有将setTimeout
包装在承诺中,则无法使用.
You cannot use setTimeout
without wrapping it in a promise.
这篇关于异步/等待超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!