signals - How to combine AbortController and AbortSignal? - Stack Overflow

To specify a timeout of a fetch request, we can use a AbortSignal.timeout() signal:await fetch(url, {s

To specify a timeout of a fetch request, we can use a AbortSignal.timeout() signal:

await fetch(url, {
  signal: AbortSignal.timeout(10 * 1000),

});

But this is just a standalone signal, not a controller.

What if I also want to control the request somewhere else in the code, and abort the request? Normally I would use AbortController for that:

const abortController = new AbortController();
await fetch(url, {
  signal: abortController.signal,

});

// now I can call abortController.abort();

But now I lose the timeout convenience. Is there any way to have both, without manually handling the timeout (with setTimeout)?

To specify a timeout of a fetch request, we can use a AbortSignal.timeout() signal:

await fetch(url, {
  signal: AbortSignal.timeout(10 * 1000),

});

But this is just a standalone signal, not a controller.

What if I also want to control the request somewhere else in the code, and abort the request? Normally I would use AbortController for that:

const abortController = new AbortController();
await fetch(url, {
  signal: abortController.signal,

});

// now I can call abortController.abort();

But now I lose the timeout convenience. Is there any way to have both, without manually handling the timeout (with setTimeout)?

Share Improve this question edited Mar 13 at 11:40 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Mar 13 at 11:25 AlexAlex 66.2k185 gold badges460 silver badges651 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You can use AbortSignal.any - it is relatively new (as of 2024), though, so keep that in mind. See the documentation up at https://developer.mozilla./en-US/docs/Web/API/AbortSignal/any_static.

Usage is:

const currentRequestController = new AbortController();

// ...

const response = await fetch('https://example/some/path', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
  },
  signal: AbortSignal.any([AbortSignal.timeout(1000), currentRequestController.signal]),
});

// ...

// can abort later or the timeout will fire... whichever occurs first
currentRequestController.abort()

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744703865a4588937.html

相关推荐

  • signals - How to combine AbortController and AbortSignal? - Stack Overflow

    To specify a timeout of a fetch request, we can use a AbortSignal.timeout() signal:await fetch(url, {s

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信