For example, you have a Web Music Player app. 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. Is there a way to just cancel the previous function completely? I know you can abort XHRequests, but I mean like whole functions. Maybe JS Promises?
-
1Depends on the function, but no, you can't just cancel any async function with some magic method.adeneo– adeneo2014-04-21 20:02:33 +00:00Commented Apr 21, 2014 at 20:02
-
1There is no way to 'cancel' a function. It has to be a part of the API. In your example it sounds like AJAX, which you can cancel.Benjamin Gruenbaum– Benjamin Gruenbaum2014-04-21 20:02:50 +00:00Commented Apr 21, 2014 at 20:02
-
You can't cancel results of functions you had already done. But you don't have this problem in your post. Restructure your model just. You don't need what you ask for that.Sharikov Vladislav– Sharikov Vladislav2014-04-21 20:10:09 +00:00Commented Apr 21, 2014 at 20:10
-
Well yeah, if I'd have a serverside page that does all the work and just returns the player or whatever, but I'm doing this all with JavaScript, meaning that I can't just do an AJAX request to a serverside script that does everything.Fabis– Fabis2014-04-21 20:58:38 +00:00Commented Apr 21, 2014 at 20:58
1 Answer
In javascript a synchronous function will run to completion. 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.
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. 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.