Skip to content

Instantly share code, notes, and snippets.

@davvit
Created November 15, 2018 19:01
Show Gist options
  • Save davvit/55e0c8dbd475a7945af5a9a68259e881 to your computer and use it in GitHub Desktop.
Save davvit/55e0c8dbd475a7945af5a9a68259e881 to your computer and use it in GitHub Desktop.
Promise with timeout
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