将参数传递给回调node.js

时间:2017-11-15 21:10:38

标签: javascript node.js asynchronous callback

我正在Node.js中开发一个RESTful应用程序,我正在使用https库实现http请求。

目前,每个文件都包含一个带有某些参数的http请求,如下面的代码所示:

//test.js

var https = require('https');

module.exports.httpResponse = function (callback) {

    var options = {
      host: 'api.github.com',
      path: '/users/Guilherme-Routar',
      method: 'GET',
      //headers: {'user-agent': userAgent} 
    }

    var str = '';

    var request = https.request(options, function (response) {

        response.on('data', function (body) {
            str += body;
        });

        response.on('end', function () {
            return callback(str);
        });
    });

    request.on('error', (e) => {
        console.log(e);
    });

    request.end();
}

现在我想将http请求本身封装在一个单独的文件中(用于重构),这样每个文件都会调用模板并将它自己的参数传递给它。但这就是问题所在。是否可以将参数传递给回调?

//test.js
var https = require('https');

//I tried adding 'options' next to the 'callback' parameter
module.exports.httpResponse = function (callback, options) {

    var str = '';
    var request = https.request(options, function (response) {

        response.on('data', function (body) {
            str += body;
        });
        response.on('end', function () {
            return callback(str);
        });
    });
    request.on('error', (e) => {
        console.log(e);
    });
    request.end();
}

在另一个文件中,我定义并传递函数的参数

//user.js    

var test = require('../test.js');

var options = {
  host: 'api.github.com',
  path: '/users/Guilherme-Routar',
  method: 'GET',
  //headers: {'user-agent': userAgent} 
}

// Passing 'options' as a parameter 
test.httpResponse(function(response, options) {
  console.log('response = ' + response);
})

但这显然不起作用。你能给我什么建议吗?提前谢谢。

1 个答案:

答案 0 :(得分:2)

似乎你想在回调之后将选项作为附加参数传递,而不是期望它在回调中传递。

而不是:

test.httpResponse(function(response, options) {
  //                                 ^ you don't want option to be part of the callback
  console.log('response = ' + response);
})

你想:

test.httpResponse(function(response) {
  console.log('response = ' + response);
}, options)
// ^ pass options as second parameter

正如Bergi在下面提到的,Node中通常的约定是将回调作为最后一个参数传递(正如你在https.request方法中看到的那样),这需要你翻转参数。你的httpResponse方法:

module.exports.httpResponse = function (options, callback) {
// ...                                  ^^^^^^^^^^^^^^^^^ flip these two so that callback is at the end
}

然后使用它:

test.httpResponse(options, function(response) {
//                ^ pass options as first parameter
  console.log('response = ' + response);
})
相关问题