异步/等待超时

新手上路,请多包涵

我使用 Node.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!!
});

关于如何解决的任何想法?

原文由 nkint 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 434
1 个回答

您可以使用 Promise.race 进行超时:

 Promise.race([
    doSomethingInSeries(),
    new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 11.5e3))
]).catch(function(err) {
    // errors in res1, res2, res3 and the timeout will be caught here
})

您不能使用 setTimeout 而不将其包装在承诺中。

原文由 Bergi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题