Skip to content

Commit

Permalink
docs: Add timeout for fetch request.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ellipse120 committed May 8, 2023
1 parent 5e3b4d5 commit a345f66
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions note.md
Original file line number Diff line number Diff line change
Expand Up @@ -4396,3 +4396,26 @@ user: {
## 156. Set a timeout for a fetch request.
```js
const abortController = new AbortController();
const signal = abortController.signal;

const fetch1 = fetch(“https://api.example.com/data-1”, { signal });
const fetch2 = fetch(“https://api.example.com/data-2”, { signal });

const timeout = new Promise((_, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error(“Request timed out”));
abortController.abort(); // Abort the fetch request
clearTimeout(timeoutId); // clear the timeout
}, 5000);
});

Promise.race([fetch1, fetch2, timeout])
.then((response) => console.log(response))
.catch((error) => console.error(error));
```
——

0 comments on commit a345f66

Please sign in to comment.