I can’t figure out how to return a value from a function which is bound to Http.onData().
My code:
var object:Dynamic;
var req = new Http( "http://localhost:8080/test_function" );
function my_function (data:String):String {
object = Json.parse(data);
req.setHeader ("Content-type", "application/json");
req.setPostData(Json.stringify(object));
req.request( true );
req.onData = function(response:String) { // my bound function
trace(response) // receive value - how to return it from "my_function" ?
}
}
I try to return a http response from “my_function”. Could you please help. I will appreciate any advice.
The onData event happens asynchronously meaning you can’t just return it from a method. The proper way to handle it would be to pass a method that accepts a string as a parameter and use the data that way.
var object:Dynamic;
var req = new Http( "http://localhost:8080/test_function");
my_function(data, function(response){
trace("Got the response via callback", response);
});
function my_function (data:String, callback:String->Void):Void {
object = Json.parse(data);
req.setHeader ("Content-type", "application/json");
req.setPostData(Json.stringify(object));
req.onData = function(response:String) { // my bound function
//trace(response) // receive value - how to return it from "my_function" ?
callback( response );
}
req.request( true );
}
Wrapping the result into a future will make your life easier:
import haxe.Http;
using tink.CoreApi;
class Test {
static function main() {
var future = Future.async(function(cb) {
var req = new Http('https://try.haxe.org');
req.onData = cb;
req.onError = function(e) trace(e);
req.request();
});
future.handle(function(o) trace(o));
}
}