Skip to content Skip to sidebar Skip to footer

Reject A Promise And Stop Timeout On Socket-io Event

I'm currently using the following function to simulate awaiting (sleep) in my Node.js server script. function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)

Solution 1:

In your case 'break' means 'early resolving', not rejecting. If you calling reject the await statement will throw an error and execution of the async function can be stopped (if try catch block is not used). The code might look a little better::

const CPromise= require("c-promise2");
// cancellable sleepfunctionsleep(ms, signal) {
    returnnewCPromise((resolve, reject, {onCancel}) => {
        const timer = setTimeout(resolve, ms);
        onCancel(() =>clearTimeout(timer));
    }, {signal}).catch(() => {});
}

(async()=>{
    const sleeper= sleep(30000);
    socket.on("end_sleep",function(){
        sleeper.cancel();
    });
    await sleeper;
})();

or

const abortController= new CPromise.AbortController();

(async()=>{
    await sleep(30000, abortController.signal);
})();

socket.on("end_sleep",function(){
    abortController.abort();
});

Solution 2:

I would be tempted to wrap this in a class which holds the state of both the timerId and the reject of the returned Promise and use them within a cancel method.

The below demonstrates this:

classSleeper
{
   wait(ms){
     returnnewPromise( (resolve, reject) => {
        this.reject = reject;
        this.t = setTimeout(resolve,ms);
     });
   }
   
   cancel(reason){
    clearTimeout(this.t);
    this.reject(reason);
   }
}
var sleep = newSleeper();

asyncfunctiontest(){
  
  try{
    await sleep.wait(5000);
    console.log("finished");
  }catch(e){
    console.log("cancelled:", e);
  }
}

document.querySelector("#cancel").addEventListener("click", () => {
   sleep.cancel("cancel button pressed");
});

test();
<buttonid="cancel">Cancel</button>

I've added the ability to pass a cancel reason, might be useful.


In your code that would look like:

var sleeper = newSleeper();

socket.on("end_sleep",function(){
  sleeper.cancel(); // pass a reason if you wanted.
})

// your codeawait sleeper.wait(20000);

Solution 3:

I'm not really sure why this works, but I thought to note down what made it work.

Everything was solved when I used resolve instead of reject as follows.

functionsleep(ms) {
  returnnewPromise(function(resolve,reject) => {
    var t = setTimeout(resolve, ms)
    // add the function as a "meetings" object property value
    meetings[endSleep] = function(){
      clearTimeout(t)
      resolve()
    }    
  });
}

If someone can explain why it works this way, please feel free to edit this answer.

Post a Comment for "Reject A Promise And Stop Timeout On Socket-io Event"