【问题标题】:HTTP request in separate function[node.js/expressjs]单独函数中的 HTTP 请求[node.js/expressjs]
【发布时间】:2015-04-19 08:24:59
【问题描述】:

通过使用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;
}

【问题讨论】:

    标签: javascript node.js asynchronous express


    【解决方案1】:

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

    exports.unitedStates = function (req, res) {
    
       // pass callback here
       japan(function (value) {
           res.send(value);  
       });
    } 
    
    function japan(cb) {
       //async call here
    
       cb(result);
    }
    

    【讨论】:

    • 正是我所需要的。完美运行:D
    猜你喜欢
    • 2017-12-06
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 2018-02-14
    相关资源
    最近更新 更多