将parameter passing给callback node.js
我在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请求本身封装在一个单独的文件中(为了重构的目的),这样每个文件都会调用这个模板并把它自己的parameter passing给它。 但问题出在这里。 是否有可能传递参数到callback?
//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); })
但是这显然不起作用。 任何build议,你可以给我? 提前致谢。
看来你想在callback之后作为附加parameter passing选项,而不是期望它在callback中传递。
代替:
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中惯常的约定是将callback作为最后一个parameter passing(正如你可以在你使用的https.request
方法中看到的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); })