Sergei Basharov
Sergei Basharov

Reputation: 53850

Can I use Dart async/await for post requests in browser?

I am using this example https://webdev.dartlang.org/articles/get-data/json-web-service as a starting point to develop Dart app consuming API endpoints data:

void saveData() {
  HttpRequest request = new HttpRequest(); // create a new XHR

  // add an event handler that is called when the request finishes
  request.onReadyStateChange.listen((_) {
    if (request.readyState == HttpRequest.DONE &&
        (request.status == 200 || request.status == 0)) {
      // data saved OK.
      print(request.responseText); // output the response from the server
    }
  });

  // POST the data to the server
  var url = "http://127.0.0.1:8080/programming-languages";
  request.open("POST", url, async: false);

  String jsonData = '{"language":"dart"}'; // etc...
  request.send(jsonData); // perform the async POST
}

I see this as a traditional callback running when something happens. Here it is executed when the response is received.

Though, I want to try the other approach, like using Futures/Promises or async/await.

Is it possible to turn this example into any of these alternatives in browser?

If so, can you please show the example how it looks when implemented as a Future or async/await?

Upvotes: 2

Views: 984

Answers (1)

Harry Terkelsen
Harry Terkelsen

Reputation: 2714

I concur with @Pacane about using the http package. It provides a much cleaner API for working with http requests, which allow you to easily use async/await.

However, you could write saveData using just the core libraries as follows (dartpad sample here: https://dartpad.dartlang.org/2ed9e39fd887b58532d42a70697ce9cd)

Future<Null> saveData() async {
  var response = await HttpRequest.postFormData(
      'http://127.0.0.1:8080/programming-languages',
      {'language': 'Dart'});
  print(response.responseText);
}

Upvotes: 2

Related Questions