JavaScript Implement Timeout to Promise with Race in 10 lines and Common Misunderstanding
It is common to implement the calling service return as Promise
and not all the time we got the built-in library to set the timeout
value.
We have to sometimes implement this ourselves.
Common Misunderstanding
Please see how the code below not working.
These looks good call the API / Service then wait to see if it is coming back and has value.
const longProcess = new Promise((resolve, reject) => {
const wait = setTimeout(() => {
clearTimeout(wait);
resolve('resolve');
}, 5000)
})
setTimeout(() => {
// See if there is a value after some time
if(longProcess) {
console.log('inside if', longProcess)
} else {
// timeout
}
}, 500)
However, then you will ALWAYS get inside that IF
because Promise { <pending> }
is always true
inside if Promise { <pending> }
Promise.race is the Answer
That additional 10 lines bring what you are trying to do.
const longProcess = new Promise((resolve, reject) => {
const wait = setTimeout(() => {
clearTimeout(wait);
resolve('resolve');
}, 5000)
})
// Here
const timeout = new Promise((resolve, reject) => {
const wait = setTimeout(() => {
clearTimeout(wait);
reject('timeout');
}, 500)
})
const race = Promise.race([
longProcess,
timeout
])
// Try-catch, Then-Catch
race.then((res) => console.log('then', res))
.catch(err => console.log('catch', err))
Now you arrive in the catch
block.
You can tweak the 5000
to 50
to see the different result where you are getting in the then
block.
Hope this help !