等待异步HTTP请求完成

时间:2013-09-10 14:43:59

标签: node.js

这个问题已经在这里以各种方式提出,我很清楚这个问题。一般的解决方案是调用回调来处理HTTP结果,但我特别想避免这种情况。

我想我可以使用“我们已经完成”的标志来保持工作正常,但这并没有按预期工作。

//
//  Test the IP the comment came-from.
//
exports.testJSON = function ( obj )
{
    var ip     = obj['ip'] || "";
    var result = null;
    var done   = false;

    //
    //  The URL request we're going to make
    //
    var options = {
        host: 'www.stopforumspam.com',
        port: 80,
        path: '/api?ip=' + ip
    };

    //
    // A GET request
    //
    var re = http.request(options, function(res) {
        var str = '';

        res.on('data', function(chunk) {
            console.log( "Got data " + chunk );
            str += chunk;
        });
        res.on('end', function() {
            console.log( "Got END" );
            result = "..... ";
            done = true;
        });
      }).on('error', function(e) {
         done = true;
         console.log("Got error: ", e);
     });

   re.end();

   while( ! done ) {
   }

   return( result );
};

可悲的是,这不起作用 - 繁忙的外观无限期地旋转,我看到没有控制台记录表明我正在接收数据。

将“process.nextTick()”添加到“while(!done){}”循环也没有任何区别。

当然,我不需要重新设计我的整个插件系统来应对不同的方法,并且更新“完成”标志的回调将以某种方式工作?

1 个答案:

答案 0 :(得分:2)

如果您的整个插件系统使用JavaScript,那么重新编写它可能不是一个坏主意。如果您不想使用回调处理异步代码,可以将promises视为管理异步代码的另一种解决方案。图书馆"q"可能是一个很好的起点。

另一种方法是使用node-fibers。我以前从未使用它,但这些例子很简单。采用正常的回调模式,例如:

console.log('waiting 2 seconds...');
setTimeout(function() {
    console.log('Finished!');
}, 2000);

使用节点光纤的类似示例:

var Fiber = require('fibers');

function wait(ms) {
    var fiber = Fiber.current;
    setTimeout(function() {
        fiber.run();
    }, ms);
    Fiber.yield();
}

Fiber(function() {
    console.log('waiting 3 seconds...');
    wait(1000);
    console.log('waiting 2 seconds...');
    wait(1000);
    console.log('waiting 1 seconds...');
    wait(1000);
    console.log('done!');
}).run();

要使节点光纤正常工作,需要做一些包装,但现在您可以避免处理回调并以同步方式使用异步代码。

相关问题