开发者

NodeJS: problem with request asynchronous, synchronous, api

开发者 https://www.devze.com 2023-02-03 01:50 出处:网络
I have problem with开发者_JS百科 trying to turn asynchronous function into synchronous. here is a method from class:

I have problem with开发者_JS百科 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.write(data);
    request.end();

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

            sys.puts(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');

Reagards

Tom


Simply use callback.

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

  result = data;

});


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

It simply cannot be done.

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 this question/answer from yesterday (or at least the answer; the question is not very well phrased).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号