首页 > 解决方案 > 如何使用异步生成器功能使客户端超时?

问题描述

如果 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如果没有解决响应,但我猜生成器的控制流与承诺不同,因为它什么也没做。

任何帮助深表感谢。谢谢。

标签: javascriptecmascript-6try-catchgeneratores6-promise

解决方案


您说的是异步生成器,但在您提供的示例代码中使用的是常规生成器。所以我有点困惑。

下面的示例代码基于异步生成器

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;
    }
}

推荐阅读