Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Execute a Promise with a timeout. If the timeout occurs before completing the Promise, it should reject.
/**
* Accepts a promise and a timeout. If the timeout reached while the promise is stil pending, it rejects with a timeout.
* @param timeout in milli
* @param promise
*/
Promise.timeout = (timeout, promise) => {
let bombId;
Promise.race([
promise,
new Promise((resolve, reject) => {
bombId = setTimeout( (timeoutx) => {
return reject('Timeout');
}, timeout, timeout);
})
]).then(res => {
return Promise.resolve(res)
})
.catch(err => {
return Promise.reject(err)
})
.finally(() => {
if (bombId) {
clearTimeout(bombId);
}
})
};
//Usage
usage = () => {
// define the promise to be performed in a due time
let handle = new Promise(function (resolve, reject) {
// ... some logic goes here ...
return resolve();
});
// execute the promise with a timeout of 10 seconds
return Promise.timeout(10000, handle);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.