[英]JavaScript: How to make a promise that never resolves or rejects
我在用:
await Promise.race([promise1, promise2]);
逻辑是如果promise1
在5s 内没有解决/拒绝,那么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'); })()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.