我和诺德在一起.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!!
});
有什么解决办法吗?