user1968307 user1968307 - 4 months ago 19
Dart Question

Using Futures with Dart

Why is the print result keep returning "asd"?

var jerl = "asd";

HttpRequest.request('Foo',
method: "GET",
requestHeaders: {"Authorization": "Secret"}).then((x) => x.responseText).then((y) => jerl = y);

print(jerl);

Answer

Async code is just scheduled for later execution and the sync code continues executing without waiting for the async code. The method you pass to Future.then(...) is executed when the scheduled async code is finished. You find a lot of such questions and examples tagged [:dart-async:] here on StackOverflow.

If you want code to be executed when the async code completed you need to chain it with then like you did with other code

var jerl = "asd";

HttpRequest.request('Foo',
  method: "GET",
  /* return */ requestHeaders: {"Authorization": "Secret"})
  .then((response) {
    var jer1 = x.responseText;
    print(jerl);
  });

You can use the async/await feature to make code look more like sync code

Future someMethod() async { // <== added `Future` and `async`
  var jerl = "asd";

  var response = await HttpRequest.request('Foo',  // <== added `await`
    method: "GET",
    requestHeaders: {"Authorization": "Secret"}).then((x) => 
  print(response.text);
}

async is contagious. There is no way to go back from async execution to sync execution. If your code calls any async method or function and you need code further down to wait for the async result, then you need to chain all following code (also in calling methods) with .then (or use async/await). For this to work you also need to return the future to the caller so he can call .then() on it.

With async/await you don't need to explicitly return the future.

async/await doesn't make async code sync (as mentioned above), it only makes it look more like sync code. The underlying behavior is identical as with then.