Javascript Node.js Http.Request回调-无法将数据传递给父函数
我对Node和Javascript还相当陌生,我正在努力使用我的第一个Node模块。我正在尝试为特定的API调用导出函数,我希望重用https.request函数,而不是在每个函数中重复代码。由于某些原因,我无法理解如何将数据传递回原始函数。这里是一个简化版本-listStuff函数将是处理各种api请求操作的众多函数之一Javascript Node.js Http.Request回调-无法将数据传递给父函数,javascript,node.js,api,rest,Javascript,Node.js,Api,Rest,我对Node和Javascript还相当陌生,我正在努力使用我的第一个Node模块。我正在尝试为特定的API调用导出函数,我希望重用https.request函数,而不是在每个函数中重复代码。由于某些原因,我无法理解如何将数据传递回原始函数。这里是一个简化版本-listStuff函数将是处理各种api请求操作的众多函数之一 'use strict'; const https = require('https'); const _ = require('underscore'); const ho
'use strict';
const https = require('https');
const _ = require('underscore');
const hostStr = 'api.server.net';
function listStuff(){
var pathStr = '/release/api/stuff';
_apiCall(pathStr);
//Would like to handle the https response data here
};
function _apiCall(pathStr){
var options = {
host: hostStr,
path: pathStr
};
var req = https.get(options, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
var responseString = '';
res.on('data', function(d){
responseString += d;
});
res.on('end', function(){
var responseObject = JSON.parse(responseString);
});
});
req.end();
req.on('error', function(e){
console.log(e);
});
};
module.exports = {
listStuff: listStuff
};
希望这有帮助。在apiCall函数中注册回调,然后检查回调参数以进行错误处理。然后,只要确保在想要结束函数调用时返回回调(在on-end或on-error处理中)
使用Promise对象的方法稍有不同。注意:我把这当作一个学习练习,希望它能有所帮助。我还没有为你写所有的代码,调试工作全是你的 首先,make_apiCall返回一个promise对象
function listStuff()
{
var pathStr = '/release/api/stuff';
var promise = _apiCall(pathStr);
promise.then( function( responceObject){
// handle response object data
});
promise.catch( function( error){
console.log( error.message); // report error
});
}
下一步是让_apiCall为它将在承诺创建的执行者内部发起的HTTPS请求返回一个承诺对象
function _apiCall(pathStr)
{ var options = {
host: hostStr,
path: pathStr
};
function beginGet( worked, failed)
{
// see below
}
return new Promise( beginGet);
}
最后,编写beginGet,根据get请求的结果启动并回调成功或失败函数
function beginGet( worked, failed)
{ var req;
var responseObj;
function getCallBack( res)
{ // all your get request handling code
// on error call failed( error)
// on sucessful completion, call worked(responseObj)
}
req = https.get(options, getCallBack);
}
另外,请查看https.get文档-我想它会为您调用req.end()。所有其他错误都是我的:-)使用回调,或者更复杂的是使用承诺。谢谢你,Bergi,这是我在阅读Node文档时收集到的信息,但在如何完成这一点上,我的大脑有点崩溃。我相信这只是我的经验不足。我曾经尝试过:_apiCall(pathStr,function(data,err){console.log(data)};在我的list-stuff函数中,它在那里崩溃了-我感觉我在正确的轨道上,但可能没有。是的,你在正确的轨道上。现在你需要让
_apiCall
函数接受这样一个函数作为附加参数(将其命名为callback
),然后在您拥有responseObject
后调用该函数。感谢Bergi-这让我走上了正确的轨道-我现在至少在回调函数中得到了一个“未定义的”返回-有点黑客行为尚未解决-如果我再次陷入困境或添加我的解决方案,我将在这里更新。
function beginGet( worked, failed)
{ var req;
var responseObj;
function getCallBack( res)
{ // all your get request handling code
// on error call failed( error)
// on sucessful completion, call worked(responseObj)
}
req = https.get(options, getCallBack);
}