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);
}
}
然后您更新了睡眠功能以了解此令牌:
function delayAsync(timeMs, cancellationToken){
return new Promise((resolve, reject) => {
setTimeout(resolve, timeMs);
if(cancellationToken)
{
cancellationToken.register(reject);
}
});
}
现在您可以使用令牌取消它传递给的异步函数:
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/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)