javascript - 单独函数中的 HTTP 请求[node.js/expressjs]

标签 javascript node.js asynchronous express

通过使用 async模块我有这样的东西,它工作得很好。 但是当我尝试重组代码或使其可重用时,它在完成 HTTP 请求之前就完成了执行。 Nodejs 以异步方式做很多事情,因此找到解决方案对我来说有点困难。

我现在有什么。

  var async = require('async'),
  http = require('http');

  exports.unitedStates = function(req, res) {

    var texas = {
      //GET method data here / ex: host, path, headers....
    };

    var washington = {
      //GET method data here / ex: host, path, headers....
    };


    async.parallel({
        getSource: function(callback) {
          http.request(texas, function(respond) {
            //Http request
          }).end();
        },
        getScreen: function(callback) {
          http.request(washington, function(respond) {
            //Http request
          }).end();
        }
      },
      function(err, results) {
        //Return the results

        /* REPLY TO THE REQUEST */
        res.send( /* data here */ );
      });

}

是否有一种完美的方法可以使这段代码可重用

例子

exports.unitedStates = function(req, res) {
  var tokyo = japan();

  //send the result to front end
  res.send(tokyo);
}

function japan(){
  //async calls comes here and return the value...
  return result;
}

最佳答案

不是从函数返回值,而是传递回调。

exports.unitedStates = function (req, res) {

   // pass callback here
   japan(function (value) {
       res.send(value);  
   });
} 

function japan(cb) {
   //async call here

   cb(result);
}

关于javascript - 单独函数中的 HTTP 请求[node.js/expressjs],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28581861/

相关文章:

javascript - JS事件队列中的事件顺序

javascript - Angular js : element. val 在指令链接函数中不起作用

javascript - 使用 Moment 为 HighCharts 输出 Date.UTC() 对象?

mysql - Nodejs Express 与 mysql 分页

javascript - 带有 Node.js 的 jQuery 数据表

javascript - connect-busboy on ('file' ) 事件未触发

c# - "Async"关键字是使 NLog 日志记录异步的唯一要求吗?

javascript - 无法使用 Sinon stub 函数

Javascript FileReader 读取文件不正确

node.js - Node 教程 - LearnYouNode - 杂耍异步 - 使用嵌套回调