我使用 Node.js 和 TypeScript,并且正在使用 async/await
。这是我的测试用例:
async function doSomethingInSeries() {
const res1 = await callApi();
const res2 = await persistInDB(res1);
const res3 = await doHeavyComputation(res1);
return 'simle';
}
我想为整个功能设置一个超时。即如果 res1
需要 2 秒, res2
需要 0.5 秒, res3
需要 5 秒我想在 3 秒后有一个超时错误。
使用正常的 setTimeout
调用是一个问题,因为范围丢失了:
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
:
doSomethingInSeries().catch(function(err) {
// errors in res1, res2, res3 will be catched here
// but the setTimeout thing is not!!
});
关于如何解决的任何想法?
原文由 nkint 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用
Promise.race
进行超时:您不能使用
setTimeout
而不将其包装在承诺中。