Created
June 2, 2020 21:28
-
-
Save paulosuzart/5f247bf8668425a3a85355ae81273536 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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