Skip to content

Instantly share code, notes, and snippets.

@paulosuzart
Created June 2, 2020 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulosuzart/5f247bf8668425a3a85355ae81273536 to your computer and use it in GitHub Desktop.
Save paulosuzart/5f247bf8668425a3a85355ae81273536 to your computer and use it in GitHub Desktop.
const promiseWithTimeout = (timeoutMs, promise, failureMessage) => {
var timeoutHandle;
const timeoutPromise = new Promise((resolve, reject) => {
timeoutHandle = setTimeout(() => reject(new Error(failureMessage)), timeoutMs);
});
return Promise.race([
promise,
timeoutPromise,
]).then((result) => {
clearTimeout(timeoutHandle);
return result;
});
}
let pa = new Promise((res, rej) => {
setTimeout(() => {
console.log('now it goes');
res("short")
}, 3000);
});
let pb = new Promise((res, rej) => {
setTimeout(() => res("long"), 5000);
});
promiseWithTimeout(1000, pa, "FalowA").then(r => console.log(r)).catch(e => console.log(e));
// promise will continue to run even after race returns a winning promise.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment