Alex.Marynovskyi
Alex.Marynovskyi

Reputation: 1334

How does Dart run asynchronous code without blocking?

How does Dart run asynchronous code without blocking? For example:

void test(User user) async {
    print('test');

    String fullName = user.firstName + ' ' + user.lastName;

    final result = await sendRequest(fullName);

    print('${result}');
}

I understand that when Dart runs async function, it executes code before await and then wraps the remaining code into Future and puts it into Event Loop. But, how does that Future what we're awaiting for (await sendRequest(fullName)) not blocking running the other, synchronous code? We should wait for request for complete but it also requires some code to check that we've received or not received response. How does it not block other operations, like button clicks?

Upvotes: 2

Views: 771

Answers (1)

lrn
lrn

Reputation: 71783

The function returns at the first await. It returns a future which will later be completed (which is then ignored because of the void return type). Everything else in the function happens in reaction to callbacks from other futures (or streams, if you use await for).

The async function here is basically rewritten into something like:

void test(User user) {
  print('test');
  String fullName = user.firstName + ' ' + user.lastName;
  return sendRequest(fullName).then((final result) { // <-- Returns here, synchronously.
    print('${result}');    // <-- Gets called by the future of `sendRequst(fullName)`.
  });
}

This transformation is similar to a continuation-passing style transformation in the it takes the continuation (the control flow in the body of the function after the await) and makes it into a function.

(In reality, the transformation is more complicated because it needs to account for loops, try/catch/finally, and even break statements. Because of that, even a simple example like this one will likely be converted into something more complicated than absolutely necessary).

Upvotes: 6

Related Questions