【问题标题】:Pass parameter to callback node.js将参数传递给回调 node.js
【发布时间】:2018-04-29 06:18:45
【问题描述】:

我正在 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);
})

但这显然行不通。你有什么建议可以给我吗?提前致谢。

【问题讨论】:

    标签: javascript node.js asynchronous callback


    【解决方案1】:

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

    代替:

    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 方法中所见),这需要您翻转 @ 的参数987654324@方法:

    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);
    })
    

    【讨论】:

    • 回调通常在最后
    • 我一直在寻找解决方案。成功了,非常感谢!
    • @Bergi 正确,已修复。
    • @Khabz 很高兴为您提供帮助
    猜你喜欢
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多