I want to create a function that only runs if a Promise resolves, and do nothing if it rejects or if a timeout is reached.
This is what I have in mind:
onlyRunIfResolvesInTime().then(function(){
// only run if resolved
})
The following code unfortunately always throws a Uncaught (in promise) two error when the timeout is reached (promise2 rejects).
// This promise would be replaced with a function
// that only can resolve under certain conditions,
// but if it can't in time we want to reject.
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, "one")
})
// This promise is the timeout that rejects if the
// time limit is reached.
const promise2 = new Promise((resolve, reject) => {
setTimeout(reject, 100, "two")
})
let onlyRunIfResolvesInTime = function () {
return Promise.race([promise1, promise2])
}
onlyRunIfResolvesInTime()
.then(() => {
console.log("running function")
})
And if I catch the error in Promise.race() like following
let onlyRunIfResolvesInTime = function () {
return Promise.race([promise1, promise2])
.catch(() => { })
}
then my onlyRunIfResolvesInTime function always resolves and runs the then function instead of doing nothing when the timeout is reached.
How can I get onlyRunIfResolvesInTime to only run if Promise.race() resolves and ignore a reject?
Just ignore the reject handle for onlyRunIfResolvesInTime
onlyRunIfResolvesInTime()
.then(() => {
console.log("running function")
})
.catch(() => null) // timed out -> do nothing
You can use a variable:
result = promise.then(
function(v) {
isRejected = false;
isPending = false;
return v;
},
function(e) {
isRejected = true;
isPending = false;
throw e;
}
);
function e() {
if(isPending===false){
setTimeout(10, e)
} else if(isRejected===true){
//rejected
} else if(isRejected===false){
//fulfilled
}
}
e()