javascript - 如何使用异步生成器功能使客户端超时?
问题描述
如果 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
如果没有解决响应,但我猜生成器的控制流与承诺不同,因为它什么也没做。
任何帮助深表感谢。谢谢。
解决方案
您说的是异步生成器,但在您提供的示例代码中使用的是常规生成器。所以我有点困惑。
下面的示例代码基于异步生成器
function promisedTimer(duration) {
return new Promise(resolve => {
setTimeout(() => resolve('Some random ID/string identifier'), duration);
})
}
async function* fn () {
try {
const result = await Promise.race([promisedTimer(2), call(...)])
if(result === "Some random ID/string identifier") {
//Clean
throw Error('Timeout');
} else {
const res = yield result;
const { data } = yield res;
}
}
catch(error) {
yield put({...error});
return error;
}
}
推荐阅读
- python - 二分查找的最长递增子序列
- python - 在 Python 中连接到 ConnectWise API
- html - 将重叠图像居中的更好方法是什么?
- c# - 在 Unity 中,C# 中的事件会触发但订阅者方法不会触发?
- python - Python Plotly Dash:自定义加载图标
- python - 仅从字符串中分离后缀
- mongodb - Vue + MongoDB + AXIOS - 将数据发布到数据库不起作用?只有第一个值?
- python - BeautifulSoup 中不必要的缩进
- azure-iot-hub - Azure IoT Edge:如何监控 IoT 中心所有设备的边缘模块(安装)状态
- windows - CMake list(APPEND ...)将正斜杠切换为反斜杠