Return string from HttpRequest

In Dart, I can do:

await HttpRequest.getString(path)

and this will return a string.

I want to create a method that will do the same, but like this:

HttpRequest request = new HttpRequest();
request
    ..open('Get',getPath)
    ..setRequestHeader('Content-Type','application/json')
    ..send('');
...
return responseString;

I can do this with events and futures, but I would like to understand how to do it with async and wait extra.

Edit: This is for dart: html HttpRequest for browser.

+4
source share
1 answer

Not tried, but I think this is what you are looking for

import 'dart:html';
import 'dart:async';

main() async {
 print(await getString());
}

Future<String> getString() async {
  String getPath = 'https://dartpad.dartlang.org/';
  HttpRequest request = new HttpRequest();
  request
    ..open('Get',getPath)
    ..setRequestHeader('Content-Type','application/json')
    ..send('');

  // request.onReadyStateChange.listen(print);
  await request.onLoadEnd.first;

  return request.responseText;
}
+5
source

Source: https://habr.com/ru/post/1623448/


All Articles