node.js - 在 Nodejs 中编写异步 http 返回

标签 node.js http asynchronous

我意识到这个问题可能会被问一百万次,但无论如何我都会尝试。因此,我习惯了 Python 和 Ruby,以及“阻塞”命令式代码块、对象和方法,并尝试为我加入的项目学习这种新奇的 Node 东西。尽管我尽了最大的努力,但我还是无法完全理解异步回调和传递返回值。

这是我的代码:

var getAnHttp = function getAnHttp (args, callback) {                   
  var req = http.request(args, callback);                               

  req.on('error', function(errmsg) {                                     
    console.log('problem with request\t' + errmsg.message);              
  });                                                                   

  req.end();                                                            
};                                                                      

var getWebPageBody = function getWebPageBody (res) {                    
  var pageRes = "";                                                     

  res.setEncoding('utf8');                                              
  res.on('data', function(requestBody) {                                
    pageRes = requestBody;                                              
    console.log('[ DEBUG ] BODY:\t' + pageRes);                         
  });                                                                   
  res.on('end', function() {                                            
    return pageRes;                                                     
  });                                                                   
};                                                                      

exports.captureLink = function captureLink(targetLink) {                
  getAnHttp(targetLink, getWebPageBody);                              
};

实际调用它:

var crawl   = require('../grab_site');

var aGreatSite    = { hostname : 'hotwebcrawlingaction.xxx',
                      port     : 80,
                      path     : '/asyncpron',
                      method   : 'GET'
                    };

var something = crawl.captureLink(aGreatSite);

getWebPageBody 将打印我的输出,但我无法让我的返回通过函数向上冒泡。我知道我正在以同步方式调用某些内容,而有些内容则以异步方式调用,但我无法完全解决这个问题。虽然我当然可以将其放入一个大函数中,但我正在尝试正确执行此操作,而不是将其破解。

无论如何,对于一个菜鸟问题感到抱歉——我觉得我正在努力同时实现功能性和OOP+命令性——我看到了很多其他例子,但我试图不去传播邪教或向玛丽致敬。

最佳答案

异步函数将永远返回必须通过异步获取的内容。在您的情况下,getWebPageBody 返回undefined,然后您的回调就会发生。

在同步编程中,您返回一个值。但在异步中,您将其作为回调函数的参数提供。

因此,让您的函数接受回调参数,并在完成后简单地调用它。

var getWebPageBody = function(res, callback) {                    
  var pageRes = "";                                                     

  res.setEncoding('utf8');                                              
  res.on('data', function(requestBody) {                                
    pageRes = requestBody;                                              
    console.log('[ DEBUG ] BODY:\t' + pageRes);                         
  });                                                                   
  res.on('end', function() {
    callback(pageRes); // invoke callback
  });
};

// and call it
getWebPageBody(res, function(pageRes) {
  // pageRes is now the thing you expect, inside this function.
});

如果您调用触发异步操作的函数,return 将永远不会从中获取任何值。这都是关于回调的。您可以从其他东西的回调中触发自己的回调。

关于node.js - 在 Nodejs 中编写异步 http 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16928838/

相关文章:

node.js - Multer 将文件上传到对象数组中

javascript - 使用 Angular js 的 Controller 中的函数

android - android中的Http Get和Post方法异常?

api - “Shared” 网站和 RESTful API 认证

c# - HttpListener 类可以用于嗅探吗?

asynchronous - 关于异步编程设计模式的资源

javascript - 是否可以在 NodeJs 中要求子 sdk 库?

node.js - 使用普通 Express.js 的分层路由

javascript - 如何从异步调用返回响应?

Java Runtime.exec() 异步输出