Created
November 15, 2018 19:01
-
-
Save davvit/55e0c8dbd475a7945af5a9a68259e881 to your computer and use it in GitHub Desktop.
Promise with timeout
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
export function PromiseWithTimeout(ms, promise) { | |
// Create a promise that rejects in x milliseconds | |
let timeout = new Promise((resolve, reject) => { | |
let id = setTimeout(() => { | |
reject('timeout'); | |
}, ms) | |
}) | |
// Returns a race between timeout and the passed in promise | |
// handle the result in the calling promise. | |
return Promise.race([ | |
promise, | |
timeout | |
]) | |
} | |
//example usage | |
raceSample() { | |
this.workingOnSmtn = true; | |
//let this be login process promise that resolves in 200ms | |
let loginP = new Promise((resolve, reject) => { | |
let wait = setTimeout(() => { | |
resolve('Promise Wins!'); | |
}, 2000) | |
}); | |
PromiseWithTimeout(2000, loginP) | |
.then((res) => { | |
this.isloggedin = true; | |
this.msg = res; //res will be 'Promise Wins' | |
console.log(res); | |
this.workingOnSmtn = false; | |
}) | |
.catch((err) => { | |
if (err == "timeout") { | |
this.isloggedin = false; | |
this.msg = err; //err will be timeout | |
console.log('Promise Timedout'); | |
this.workingOnSmtn = false; | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment