问题
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();
});
回答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)
回答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:
- Use Typescript to get es6 features and async/await.
- Use Bluebird for promises in all environments to get sound promise cancellation support.
- Use cancelable-awaiter which makes Bluebird cancellations play nice with async/await in Typescript.
来源:https://stackoverflow.com/questions/32897385/abort-ecmascript7-async-function