Created
March 4, 2018 17:47
-
-
Save sobstel/fb854a6e7152577b28f2647d157829ae to your computer and use it in GitHub Desktop.
fetch with timeout
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 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