中止ecmascript7异步功能

Yuk*_*élé 4 javascript promise cancellation es6-promise ecmascript-next

有没有办法取消ES7异步功能?

在这个例子中,单击时,我想在调用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();
});
Run Code Online (Sandbox Code Playgroud)

spe*_*der 6

JavaScript还没有内置,但你可以很容易地自己动手.

MS.Net使用取消令牌的概念来取消任务(.net相当于Promises).它工作得非常好,所以这里是JavaScript的简化版本.

假设您创建了一个旨在表示取消的课程:

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

然后你更新了你的睡眠功能以了解这个标记:

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

现在,您可以使用令牌取消传递给它的异步函数:

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

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

...或者使用async/await样式或多或少做同样的事情:

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