Skip to content Skip to sidebar Skip to footer

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(;;){ drawRandomRe

Solution 1:

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)

Solution 2:

Unless your question is purely theoretical, I assume you are using Babel, Typescript or some other transpiler for es6-7 support and probably some polyfill for promises in legacy environments. Though it's hard to say what will become standard in the future, there is a non-standard way to get what you want today:

  1. Use Typescript to get es6 features and async/await.
  2. Use Bluebird for promises in all environments to get sound promise cancellation support.
  3. Use cancelable-awaiter which makes Bluebird cancellations play nice with async/await in Typescript.

Post a Comment for "Abort Ecmascript7 Async Function"