【发布时间】:2018-11-30 08:44:26
【问题描述】:
如果 try 块在一定时间内没有解决,我想强制 catch 语句处理错误。下面是我试图实现的代码。
function* fn () {
try {
// if the following line doesn't resolve within 2ms
// how can I throw an error that the catch block below will handle?
// This line would be making a call to an API.
// Regardless of the server's expiration, I want to simulate
// a timeout after n seconds, cancel the request & exit the function.
const res = yield call(...);
const { data } = yield res;
}
catch(error) {
yield put({...error});
return error;
}
}
我最初尝试在一个装饰器函数中装饰 const res = yield call(...) 语句,该函数创建一个 new Promise 并声明一个超时 rejects 如果未解决则响应,但我猜生成器的控制流不一样就像承诺一样,它什么也没做。
非常感谢任何帮助。 谢谢。
【问题讨论】:
-
可能是
Promise.race的候选人 -
那么,
call()返回一个你想超时的承诺?
标签: javascript ecmascript-6 try-catch generator es6-promise