JavaScript:如何做出永远不会解决或拒绝的承诺

run*_*ace 2 javascript promise

我在用:

 await Promise.race([promise1, promise2]);
Run Code Online (Sandbox Code Playgroud)

逻辑是如果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( () => {} )
}
Run Code Online (Sandbox Code Playgroud)

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

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

Tib*_* C. 8

直接回答你的问题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');
Run Code Online (Sandbox Code Playgroud)

但我想你有不同的问题。

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.
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)