如何在不解决Promise的情况下处理Promise.race()中的拒绝



我想创建一个函数,它只在Promise解析时运行,而在它拒绝或达到超时时不执行任何操作。

这就是我的想法:

onlyRunIfResolvesInTime().then(function(){
// only run if resolved
})

不幸的是,当达到超时时,以下代码总是抛出Uncaught (in promise) two错误(promise2拒绝(。

// 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")
})

如果我在Promise.rece((中发现错误,就像在中一样

let onlyRunIfResolvesInTime = function () {
return Promise.race([promise1, promise2])
.catch(() => { })
}

那么我的CCD_ 3函数总是解析并运行CCD_。

如何使onlyRunIfResolvesInTime仅在Promise.race()解析并忽略拒绝时运行?

只需忽略onlyRunIfResolvesInTime的拒绝句柄

onlyRunIfResolvesInTime()
.then(() => {
console.log("running function")
})
.catch(() => null) // timed out -> do nothing

您可以使用一个变量:

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()

最新更新