Question

Here is a problem. When I ran these code:

String responseText = null;

HttpRequest.getString(url).then((resp) {
    responseText = resp;
    print(responseText);
    });
print(responseText);

In console:

{"meta":{"code":200},"data":{"username":"kevin","bio":"CEO \u0026 Co-founder of Instagram","website":"","profile_picture":"http:\/\/images.ak.instagram.com\/profiles\/profile_3_75sq_1325536697.jpg","full_name":"Kevin Systrom","counts":{"media":1349,"followed_by":1110365,"follows":555},"id":"3"}}
null

It running asynchronously. Is there JAVA way with synchronized method? That will be await while request is done? I found only one tricky way to do it and its funny -- wait for three seconds:

handleTimeout() {
    print(responseText);
}
const TIMEOUT = const Duration(seconds: 3);
new Timer(TIMEOUT, handleTimeout);

And of course it works with bugs. So any suggestions?

MattB way work well:

  var req = new HttpRequest();
  req.onLoad.listen((e) {
     responseText = req.responseText;
     print(responseText);
   });
   req.open('GET', url, async: false);
   req.send();
Was it helpful?

Solution

First, I'm assuming you're using this as a client-side script and not server-side. Using HttpRequest.getString will strictly return a Future (async method).

If you absolutely must have a synchronous request, you can construct a new HttpRequest object and call the open method passing the named parameter: async: false

var req = new HttpRequest();
req.onLoad.listen((e) => print(req.responseText));
req.open('GET', url, async: false);
req.send();

However it is highly recommended that you use async methods for accessing network resources as a synchronous call like above will cause the script to block and can potentially make it appear as though your page/script has stopped responding on poor network connections.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top