【发布时间】:2020-07-01 08:26:19
【问题描述】:
对不起我的英语不好!
我有这样的代码结构:
var fooResolved;
int();
setTimeout(() => fooResolved(), 3000); // Just for testing we resolve the foo using a timeout manually
async function int(){
await foo('usage');
console.log('foo Resolved'); // if we see this log the foo is resolved
}
// this is my code structure I just put a switch inside the foo function nothing special
async function foo(type){
switch (type) {
case 'usage':
mm();
async function mm() {
await a();
await b();
await c();
await d();
fooResolved();
}
break;
}
return new Promise((resolve) => {
fooResolved = resolve;
});
} // End of foo function
// These are our a and b and c and d function all same as they resolve by a timeout in 2 seconds
function a() {
console.log('a');
return new Promise(resolve => {
setTimeout(() => resolve(), 2000);
});
}
function b() {
console.log('b');
return new Promise(resolve => {
setTimeout(() => resolve(), 2000);
});
}
function c() {
console.log('c');
return new Promise(resolve => {
setTimeout(() => resolve(), 2000);
});
}
function d() {
console.log('d');
return new Promise(resolve => {
setTimeout(() => resolve(), 2000);
});
}
如您所见,我们解决了 foo 函数,而还有两个函数(c 和 d)尚未解决。
如果我们想在执行fooResolved() 时中断foo 函数,这样我们就不需要解析剩余的函数了怎么办?
我的意思是我们不应该在上面的代码中看到c 和d 日志...
一个
b
foo 已解决
如果我们在c 之后立即执行fooResolved(),我们应该会看到这个等等...
一个
b
c
foo 已解决
请注意,在最后一个示例中,d 永远不会被执行。
非常感谢基于我的代码结构的答案和 cmets...
【问题讨论】:
-
您可以设置一个标志并在两行之间添加一个检查
if (cancelled) return。或者使用 interruptible-tasks 之类的库
标签: javascript promise async-await cancellation