Javascript 函数调用Node.js库中的其他函数时出现问题
我是新来的 我将一堆前置函数从我的库移到了一个新的Node.js库中 我知道您必须将其放入模块中。导出={ 所有功能必须采用以下格式: Hrenheit:函数(tempInC){ 我从另一个脚本调用函数很好,但函数之间的调用有问题:Javascript 函数调用Node.js库中的其他函数时出现问题,javascript,node.js,Javascript,Node.js,我是新来的 我将一堆前置函数从我的库移到了一个新的Node.js库中 我知道您必须将其放入模块中。导出={ 所有功能必须采用以下格式: Hrenheit:函数(tempInC){ 我从另一个脚本调用函数很好,但函数之间的调用有问题: tempToFahrenheit: function(tempInC){ tempInF = (tempInC*1.8)+32; return tempInF; }, getTextWeatherUsingStationUsingRequest:
tempToFahrenheit: function(tempInC){
tempInF = (tempInC*1.8)+32;
return tempInF;
},
getTextWeatherUsingStationUsingRequest: function(theStation){
const http = require("http");
const https = require("https");
// theURL = 'https://api.weather.gov/stations/' + theStation + '/observations/current';
thePath = '/stations/' + theStation + '/observations/current';
function requestTheData(){
var returnedJSON;
var options = {
protocol: "https:",
hostname: "api.weather.gov",
path: thePath,
method: "GET",
headers: {
'Accept' : 'application/json',
'Content-Type': 'application/json',
'User-Agent' : 'MY-TEST-UA'
}
};
var req= https.request(options);
var theData = '';
req.on("response", function(res){
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
theData += chunk;
});
res.on('end', () => {
console.log('No more data in response.');
returnedJSON = JSON.parse(theData);
console.log(returnedJSON.id);
// Why can't ot find temptoFahrenheit
theTemp = Math.round( tempToFahrenheit(returnedJSON.properties.temperature.value) )
windSpeed = Math.round(returnedJSON.properties.windSpeed.value);
pressure = returnedJSON.properties.barometricPressure.value;
在本文的正上方,您将看到一行代码试图在函数GetTextWeatherUsingStationSingRequest()中调用TestOfAherHeit()。我该如何实现这一点?您必须为Node.js设置函数的奇怪方式(右散列?)这些函数似乎互不具有访问权限
另一个更一般的问题。Node.js的好处应该是您在前端和后端使用Javascript,并且您可以重用代码,就像在库中一样。但正如我们在这里看到的,我必须使其非常重要(并且容易出错)更改代码以使其与节点一起工作。此外,我必须保留库的两个副本,一个前端,另一个节点。在节点中创建库不是有更好的方法吗?在节点库中,所有函数都是公共对象的成员(
模块.导出
)。因此,当您要从另一个函数调用一个函数时,必须指定调用的是this.someFunction
,而不仅仅是someFunction
(后者将查找不存在的全局可访问的someFunction
)
但是,如果您在您的案例中尝试这样做,则会使事情进一步复杂化,此
将引用不正确的上下文,因为该调用嵌套在两个异步回调(req.on
和res.on
)中。因此,您也会遇到同样的问题
要解决此问题,请尝试在GetTextWeatherUsingStationSingRequest
函数的开头添加var self=this;
,然后将AtterOfAhenheit
函数调用更改为self.AtterOfAhenheit
(变量
self
将通过调用的功能通过回调正确传播。此
不会这样做,因为它是一个始终引用当前上下文的保留关键字。)是否在对象中声明这些函数?{tentofahernheit:…,otherfunction:…}
?@GeorgeBailey yes module.exports={testofahrenheit:…,otherfunction:…}