Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abort ecmascript7 async function

Is there a way to cancel a ES7 async function?

In this example, on click, I want to abort async function call before calling new.

async function draw(){
  for(;;){
    drawRandomRectOnCanvas();
    await sleep(100);
  }
}

function sleep(t){
  return new Promise(cb=>setTimeout(cb,t));
}

let asyncCall;

window.addEventListener('click', function(){
  if(asyncCall)
    asyncCall.abort(); // this dont works
  clearCanvas();
  asyncCall = draw();
});
like image 506
Yukulélé Avatar asked Jan 07 '23 11:01

Yukulélé


1 Answers

There's nothing built in to JavaScript yet, but you could easily roll your own.

MS.Net uses the concept of a cancellation token for the cancelling of Tasks (the .net equivalent of Promises). It works quite nicely, so here's a cut-down version for JavaScript.

Say you made a class that is designed to represent cancellation:

function CancellationToken(parentToken){
  if(!(this instanceof CancellationToken)){
    return new CancellationToken(parentToken)
  }
  this.isCancellationRequested = false;
  var cancellationPromise = new Promise(resolve => {
    this.cancel = e => {
      this.isCancellationReqested = true;
      if(e){
        resolve(e);
      }
      else
      {
        var err = new Error("cancelled");
        err.cancelled = true;
        resolve(err);
      }
    };
  });
  this.register = (callback) => {
    cancellationPromise.then(callback);
  }
  this.createDependentToken = () => new CancellationToken(this);
  if(parentToken && parentToken instanceof CancellationToken){
    parentToken.register(this.cancel);
  }
}

then you updated your sleep function to be aware of this token:

function delayAsync(timeMs, cancellationToken){
  return new Promise((resolve, reject) => {
    setTimeout(resolve, timeMs);
    if(cancellationToken)
    {
      cancellationToken.register(reject);
    }
  });
}

Now you can use the token to cancel the async function that it was passed to:

var ct = new CancellationToken();
delayAsync(1000)
    .then(ct.cancel);
delayAsync(2000, ct)
    .then(() => console.log("ok"))
    .catch(e => console.log(e.cancelled ? "cancelled" : "some other err"));

http://codepen.io/spender/pen/vNxEBZ

...or do more or less the same thing using async/await style instead:

async function Go(cancellationToken)
{
  try{
    await delayAsync(2000, cancellationToken)
    console.log("ok")
  }catch(e){
    console.log(e.cancelled ? "cancelled" : "some other err")
  }
}
var ct = new CancellationToken();
delayAsync(1000).then(ct.cancel);
Go(ct)
like image 168
spender Avatar answered Jan 18 '23 20:01

spender