Skip to content

Instantly share code, notes, and snippets.

@sobstel
Created March 4, 2018 17:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sobstel/fb854a6e7152577b28f2647d157829ae to your computer and use it in GitHub Desktop.
Save sobstel/fb854a6e7152577b28f2647d157829ae 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