NodeJS: problema con la solicitud asincrónica, síncrona, api

I have problem with trying to turn asynchronous function into synchronous.

here is a method from class:

doPost: function(call, data) {

    var uri = 'http://localhost/api/'+call;

    var api = http.createClient(80, 'localhost');

    var domain = 'localhost';

    var request = api.request("POST", uri,
                        {'host' : domain,
                         'Content-Type' : 'application/x-www-form-urlencoded', 
                         "User-Agent": this.userAgent,
                         'Content-Length' : data.length


    request.on('response', function (response) {  
        response.on ('data', function (chunk) {


            try {
                var result = JSON.parse(chunk);                    
                //------------ the problem

                return HOW_TO_RETURN_RESULT;

                //------------ /the problem
            }catch (err) {
                return {'ok': 0, 'err': err}



Want to use this function in this way:

result = obj.doPost('getSomeData.php', '&data1=foo&data2=bar');



preguntado el 09 de enero de 11 a las 13:01

2 Respuestas

Simply use callback.

obj.doPost('getSomeData.php', '&data1=foo&data2=bar', function(data) {

  result = data;


Respondido el 09 de enero de 11 a las 16:01

That does not turn it into a synchronous function. It does exactly the opposite of that. (But on the other hand, it is of course exactly how this function should be used). - James

It is impossible to turn an asynchronous function into a synchronous one.

Simplemente no se puede hacer.

Instead, you must pass a callback to your function and receive the "return value" in async fashion.

In theory though, you could write some code to block your function from returning until some condition is met (ie, until the async operation is complete), but that would also require the program to be able do other things on another thread while the block is executing, which is probably not possible in node. And even if it were, it would be a world class antipattern and crime against node.js and all things evented and probably summon a velociraptor.

Conclusion: Learn how to work with asynchronous code. Also, you might be interested in reading este question/answer from yesterday (or at least the answer; the question is not very well phrased).

contestado el 23 de mayo de 17 a las 15:05

I read about "promises" in node.js but can't find any example that fit to my code. - tom

Promises are pretty much callbacks in disguise - James

Also, even if promises did what you wanted them to, node.js doesn't have them: - James

Ahora estan EventEmitters. - b_erb

@Jakob thanks - I was fighting with asynchronous with no reason :) - tom

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.