简体   繁体   English

如何中止JavaScript异步功能?

[英]How to abort JavaScript async functions?

For example, you have a Web Music Player app. 例如,您有一个Web Music Player应用程序。 When a user clicks on the play button, a function fires, looking for the MP3 data, setting up the player etc. etc., but then the user changes his mind and clicks play on another track. 当用户单击播放按钮时,会触发一个功能,查找MP3数据,设置播放器等,然后用户改变主意并单击另一首曲目上的播放。 Is there a way to just cancel the previous function completely? 有没有办法完全取消以前的功能? I know you can abort XHRequests, but I mean like whole functions. 我知道您可以中止XHRequests,但是我的意思是像整个函数一样。 Maybe JS Promises? 也许JS Promises?

In javascript a synchronous function will run to completion. 在javascript中,同步功能将运行完毕。 It will not be interrupted by another user action. 它不会被其他用户操作打断。 So, in your scenario if a function fires and is setting up the player, that function will run to completion before the next user event is processed. 因此,在您的方案中,如果某个功能触发并正在设置播放器,则该功能将在处理下一个用户事件之前运行完毕。 So, you can't abort a synchronous function in javascript and there would be no way to anyway because (except for web workers which isn't what we're discussing here), javascript is single thread so as long as function is running, it will run to completion and no other user events will be processed. 因此,您无法中止javascript中的同步函数,而且无论如何都将无法进行,因为(网络工作人员除外,这不是我们在此处讨论的内容),javascript是单线程的,只要函数正在运行,它将运行完成,并且不会处理其他用户事件。

If, however, that function has some sort of asynchronous operation in it (such as loading something via ajax or a player loading a music file), then whether or not that async operation can be aborted depends entirely upon the specific support in that operation - there is no generic abort. 但是,如果该函数中包含某种异步操作(例如通过ajax加载某些内容或加载音乐文件的播放器),则该异步操作是否可以中止完全取决于该操作的特定支持-没有通用中止。 For us to help you with asynchronous details, you would need to disclose your actual code so we can see what you're doing. 为了帮助我们提供异步详细信息,您需要公开您的实际代码,以便我们了解您的工作。

Promises are not a tool for aborting asynchronous operations. 承诺不是中止异步操作的工具。 In fact, they are a tool for somewhat the opposite as they report on what and when things happened to asynchronous operations. 实际上,它们是相反的工具,因为它们报告异步操作发生的情况和时间。 They don't cause those things to happen, then just notify observers when things happened to asynchronous operations. 它们不会导致这些事情发生,而只是在异步操作发生事情时通知观察者。


As is generally the case with StackOverflow questions, we can help much more in-depth if you disclose your actual code because that would change your question from a theoretical discussion to a practical analysis of what the options are for your actual code. 与StackOverflow问题通常一样,如果您公开实际的代码,我们可以提供更深入的帮助,因为这会将您的问题从理论讨论变为对实际代码选项的实际分析。

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

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