Skip to content

Instantly share code, notes, and snippets.

@raaar
Last active July 19, 2022 14:23
Show Gist options
  • Save raaar/3e487e4ca86cb3e8f3795ddd2476f977 to your computer and use it in GitHub Desktop.
Save raaar/3e487e4ca86cb3e8f3795ddd2476f977 to your computer and use it in GitHub Desktop.
Promise.race with AbortController
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