【发布时间】:2016-09-04 08:27:12
【问题描述】:
我使用的是 Node.js 和 TypeScript,我使用的是 async/await。
这是我的测试用例:
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 秒后让我抛出一个错误。
正常的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!!
});
关于如何解决的任何想法?
【问题讨论】:
-
你在使用特定的 promise 库吗?
-
不,只是标准的承诺。
-
所以 2 + 0.5 + 5 + 3 超时 11.5 秒?
标签: node.js typescript timeout promise async-await