COMMUNITY

Http request - return from onData() method [SOLVED]


(Peter Wachowsky) #1

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.


(Phil Chertok) #3

Peter,

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 ); 	
}


(Peter Wachowsky) #4

Thank you Phil. This is exactly what I was trying to figure out. I didn’t know that in Haxe callback functions can be used in this way.

Regards.


(Kevin Leung) #5

Wrapping the result into a future will make your life easier:

https://try.haxe.org/#C9B81

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));
    }
}