Last active
July 19, 2022 14:23
-
-
Save raaar/3e487e4ca86cb3e8f3795ddd2476f977 to your computer and use it in GitHub Desktop.
Promise.race with AbortController
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const BLOG_POSTS_URL = 'https://jsonplaceholder.typicode.com/posts'; | |
const FETCH_TIMEOUT = 3000; | |
const FETCH_INTERVAL = 4000; | |
const TIMEOUT_ERROR_MESSAGE = 'Request timed out'; | |
const controller = new AbortController() | |
const getPosts = (signal) => fetch(BLOG_POSTS_URL, { | |
signal | |
}) | |
const timeoutRequest = () => new Promise((resolve, reject) => { | |
setTimeout(() => { | |
reject(new Error(TIMEOUT_ERROR_MESSAGE)) | |
}, FETCH_TIMEOUT) | |
}) | |
let requestCount = 0 | |
const polling = setInterval(() => { | |
Promise.race([getPosts(controller.signal), timeoutRequest()]) | |
.then(response => response.json()) | |
.then(data => console.log("Data", data)) | |
.catch(error => console.error(error)) | |
requestCount++ | |
if(requestCount > 2) { | |
clearInterval(polling) | |
} | |
}, FETCH_INTERVAL) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment