gpt4 book ai didi

JavaScript:如何做出永不解决或拒绝的 promise

转载 作者:行者123 更新时间:2023-12-02 01:46:27 24 4
gpt4 key购买 nike

我正在使用:

 await Promise.race([promise1, promise2]);

逻辑是如果 promise1 没有在 5 秒内解决/拒绝,那么 promise2 可能能够解决。所以在延迟 promise2 尝试做它的事情之后,如果它失败了,我希望 promise2 返回一个永远不会解决的 Promise ,所以它的全部直到等待 promise1

我试过了

async function promise2(timeout=5000) {
await new Promise(resolve => setTimeout(resolve, timeout));
if (didStuffAndOK()) {
return "OK"
}
return new Promise( () => {} )
}

return new Promise( () => {} ) 似乎被解释为 promise 被拒绝而不是从未解决。

如何做出空洞的 promise (不是在现实生活中,而是在 JavaScript 中)?

最佳答案

直接回答你的问题 new Promise( () => {} ) 永远不会解决。

这是教授:

new Promise(()=>{})
.then(()=> console.log('promise resolved'))
.catch(()=>console.log('promise rejected'));
console.log('FOO, so that you can see that the code was executed');

但我想你有一个不同的问题。

The logic is if promise1 has not resolved/rejected within 5s, then promise2 
might be able to resolve. So after a delay promise2 tries to do its thing, if it
fails I wish to have promise2 return a Promise that never resolves so that its
all up to waiting for promise1.

为此,您可以在 promise2 中解析 promise1,因为 promise 是可链接的。

(async ()=>{

const promise1 = new Promise(()=>{}) // simulating here a very long fetch;

const promise2 = new Promise((res)=>{

setTimeout(()=>{
try {
console.log('one second passed and the fetch is still running');
throw Error() // simulating a promise2 does it thing and fails
} catch (e){
res(promise1); // Chain promise1 back
}
}, 1000);
});
await Promise.race([promise1, promise2]);
console.log('This won\'t be printed because the previous line awaits for promise1');
})()

关于JavaScript:如何做出永不解决或拒绝的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70846683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com