Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for async task to finish

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.

like image 643
Code Different Avatar asked Sep 10 '13 22:09

Code Different


People also ask

How do you wait for an async task to finish?

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.

Is async task deprecated?

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.

What does await task Completedtask do?

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.

How do you wait a method in C#?

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.


1 Answers

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.

like image 181
bitoiu Avatar answered Sep 24 '22 23:09

bitoiu