Nothing is built into JavaScript yet, but you can easily collapse yours.
MS.Net uses the cancellation token concept to cancel tasks (equivalent to .net Promises). It works very well, so the JavaScript version is cut here.
Suppose you created a class designed to indicate 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 keep abreast of this token:
function delayAsync(timeMs, cancellationToken){
return new Promise((resolve, reject) => {
setTimeout(resolve, timeMs);
if(cancellationToken)
{
cancellationToken.register(reject);
}
});
}
, async, :
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
... , async/wait:
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)