Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript: How to make a promise that never resolves or rejects

I am using:

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

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.

I tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

return new Promise( () => {} ) seems to be interpreted as the promise being rejected rather than never resolved.

How does one make an empty promise (not in real life, in JavaScript)?

>Solution :

To answer straight your question new Promise( () => {} ) never resolves.

Here is the prof :

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');

But I guess you have a diffrent question.

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.

For this you can resolve in the promise2 the promise1, because promises are chainable.

(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');
})()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading