简体   繁体   English

如何使用 AbortController 拒绝子 Promise

[英]How to reject child Promise using AbortController

I just learned about how to reject a Promise by using the AbortController API .我刚刚了解了如何使用AbortController API 拒绝 Promise It's working fine but when the promise to reject as a "child Promise", this one will still continue running even if the parent Promise is rejected.它工作正常,但是当 promise 拒绝作为“子承诺”时,即使父 Promise 被拒绝,这个仍然会继续运行。

Is there a way, when the parent is rejected, to stop the children too?有没有办法,当父母被拒绝时,也阻止孩子?

In this example, this means that there is no more running log after the rejected log when you click on the cancel button:在此示例中,这意味着当您单击取消按钮时,在rejected日志之后不再有running日志:

 let controller = new AbortController(); new Promise((resolve, reject) => { setInterval(() => console.log("running"), 500) controller.signal.addEventListener('abort', () => { console.log("rejected") reject(); }); }); function cancel() { controller.abort(); }
 <button onclick="cancel()">Cancel async loop</button>

Promise and abort controller are fine it's your timer function that needs to be cleared. Promise 和中止 controller 很好,需要清除的是你的计时器 function。

When you declare setInterval it returns an id that can be referenced later to clear the timer.当您声明setInterval时,它会返回一个 id,稍后可以引用该 id 来清除计时器。

So, when you reject the promise you need to clear it.因此,当您拒绝 promise 时,您需要清除它。

 let controller = new AbortController(); new Promise((resolve, reject) => { const id = setInterval(() => console.log("running"), 500) controller.signal.addEventListener('abort', () => { console.log("rejected"); clearInterval(id); reject(); }); }); function cancel() { controller.abort(); }
 <button onclick="cancel()">Cancel async loop</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM