Quiero crear una función que solo se ejecute si se resuelve una Promesa, y no haga nada si se rechaza o si se alcanza un tiempo de espera.
Esto es lo que tengo en mente:
onlyRunIfResolvesInTime().then(function(){ // only run if resolved }) Desafortunadamente, el siguiente código siempre arroja un error Uncaught (in promise) two cuando se alcanza el tiempo de espera ( promise2 rechaza).
// 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") })Y si detecto el error en Promise.race() como sigue
let onlyRunIfResolvesInTime = function () { return Promise.race([promise1, promise2]) .catch(() => { }) } entonces mi función onlyRunIfResolvesInTime siempre resuelve y ejecuta la función then en lugar de no hacer nada cuando se alcanza el tiempo de espera.
¿Cómo puedo hacer que onlyRunIfResolvesInTime solo se ejecute si Promise.race() resuelve e ignora un rechazo?
Simplemente ignore el identificador de rechazo para onlyRunIfResolvesInTime
onlyRunIfResolvesInTime() .then(() => { console.log("running function") }) .catch(() => null) // timed out -> do nothingPuedes usar una 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()