I'm interacting with a third-party JavaScript library where some function calls are asynchronous. Instead of working the asynchronous logic into my application, I preferred to write synchronous wrappers to those async calls. I know, I know, it's terrible design, but this is a demo project with very high chance of being rewritten entirely. I need something to show the team the concept, not really having to worry performance, yet.
Here's what I wanna do:
function sync_call(input) { var value; // Assume the async call always succeed async_call(input, function(result) {value = result;} ); return value; }
I tried the jQuery's deferred and promise but it seems to be aiming at the async design pattern. I want to use the synchronous pattern in my code.
You will need to call AsyncTask. get() method for getting result back and make wait until doInBackground execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.
This class was deprecated in API level 30. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.
It is there to make it easier for later stage to implement async code calls without having to alter the signature thus preventing having to refactor the calling code.
Example 02: Using the Delay Method to Delay a Task for a Few Seconds in Ubuntu 20.04. In this example, we will use a simple Delay() function in a C# program to delay a task for a few seconds. We'll call the Delay() method from the “Systems Threading Tasks” namespace in this example.
This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.
Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.
function f(input, callback) { var value; // Assume the async call always succeed async_call(input, function(result) { callback(result) }; }
The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With