【问题标题】:How to client-side timeout with an async generator function?如何使用异步生成器功能使客户端超时?
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2011-04-13
    • 2013-07-16
    相关资源
    最近更新 更多