Forked from john-doherty/javascript-promise-timeout.js
Created
October 27, 2018 17:57
-
-
Save dhilip89/b1270f2a7a3b8aa62361305e2c693619 to your computer and use it in GitHub Desktop.
Adds a timeout to a JavaScript promise, rejects if not resolved within timeout period
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
/** | |
* wraps a promise in a timeout, allowing the promise to reject if not resolve with a specific period of time | |
* @param {integer} ms - milliseconds to wait before rejecting promise if not resolved | |
* @param {Promise} promise to monitor | |
* @Example | |
* promiseTimeout(1000, fetch('https://courseof.life/johndoherty.json')) | |
* .then(function(cvData){ | |
* alert(cvData); | |
* }) | |
* .catch(function(){ | |
* alert('request either failed or timedout'); | |
* }); | |
*/ | |
function promiseTimeout(ms, promise){ | |
return new Promise(function(resolve, reject){ | |
// create a timeout to reject promise if not resolved | |
var timer = setTimeout(function(){ | |
reject(new Error("promise timeout")); | |
}, ms); | |
promise | |
.then(function(res){ | |
clearTimeout(timer); | |
resolve(res); | |
}) | |
.catch(function(err){ | |
clearTimeout(timer); | |
reject(err); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment