Created
February 15, 2021 09:03
-
-
Save taai/6a467a3efaf0d7d46bb99158b56a042f to your computer and use it in GitHub Desktop.
JavaScript AbortController example for custom async function
This file contains hidden or 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
function getUserById(userId, signal) { | |
if (signal.aborted) { | |
return Promise.reject(new DOMException('The API request was aborted.', 'AbortError')); | |
} | |
return new Promise(function(resolve, reject) { | |
const jobTimeout = setTimeout(function() { | |
signal.removeEventListener('abort', abortHandler); | |
resolve({ id: userId, name: 'John' }); | |
}, 3000); | |
const abortHandler = function() { | |
clearTimeout(jobTimeout); | |
reject(new DOMException('The API request was aborted.', 'AbortError')); | |
}; | |
signal.addEventListener('abort', abortHandler); | |
}); | |
} | |
(async function() { | |
const abortController = new AbortController(); | |
setTimeout(function() { | |
abortController.abort(); | |
}, 1000); | |
// or test what happens when already aborted | |
//abortController.abort(); | |
try { | |
const user = await getUserById(123, abortController.signal); | |
console.info(user); | |
} catch (e) { | |
if (e instanceof DOMException && e.name === 'AbortError') { | |
console.error('The request was aborted.', e); | |
} else { | |
console.error('There was unexpected error.', e); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment