Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for async to be completed

Tags:

flutter

dart

I currently have something like this

   Future<bool>  checkAvailability(String email) async {
        var client = new http.Client();
        var response = await client.get(host);
        bool result;
        if (response.statusCode == 404) {
             result= true;
        }
        else if (response.statusCode == 200) {
              result= false;
        }
        client.close();
        return result;
    }

I am calling the above method from a regular non-aysnc function in this way

void test() {
    checkAvailability(email).then((result){....}
       );
}

The problem with the above code is that its async. From what I understand is that Once checkAvailability is called its launched in a different thread ? and the ui (main) thread continues? Am I correct?

What I would like to do is to have test function wait for the result of checkAvailability. I know I can use await but then the method test will need to be marked as async and when this method is called it will be launched in a different thread. What I want is for the call to checkAvailability be synchronous and I don't mind waiting for a response.

like image 717
MistyD Avatar asked Oct 30 '25 03:10

MistyD


1 Answers

Once checkAvailability is called its launched in a different thread ?

Async execution is not related to threads, async works with an event queue https://webdev.dartlang.org/articles/performance/event-loop

test will need to be marked as async and when this method is called it will be launched in a different thread.

As mentioned before, it won't be another thread. Using async on a test method usually works fine. Why do you try to avoid it?

What I want is for the call to checkAvailability be synchronous and I dont mind waiting for a response.

If you don't care about the result, just don't await it, although this would also cause the calling code to continue before checkAvailability was completed.

What I want is for the call to checkAvailability be synchronous and I dont mind waiting for a response.

There is no way to go back from async execution to sync execution. Once an async call is made, it's completion and the result will always be a Future and needs to be awaited or handled by .then(...).

If you don't care when checkAvailability completes and don't need a result from async calls it makes, then you don't need to await or use then(...). Just call the method and that's it.

like image 99
Günter Zöchbauer Avatar answered Oct 31 '25 16:10

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!