Skip to content

Instantly share code, notes, and snippets.

@oleoneto
Forked from sobstel/fetch_with_timeout.js
Created August 21, 2019 19:08
Show Gist options
  • Save oleoneto/a5586aa5c559ee665674e33db58566e4 to your computer and use it in GitHub Desktop.
Save oleoneto/a5586aa5c559ee665674e33db58566e4 to your computer and use it in GitHub Desktop.
fetch with timeout
const API_URL = '...';
const TIMEOUT = 10; // seconds
export default (path) => {
/* global fetch */
const req = fetch(API_URL + path);
const timeout = new Promise((resolve, reject) => {
return setTimeout(() => reject(new Error('request timeout')), TIMEOUT * 1000);
});
return Promise.race([req, timeout]).then(response => response.json());
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment