【问题标题】:Problems with functions calling other functions in a Node.js library函数调用 Node.js 库中的其他函数的问题
【发布时间】:2023-03-04 07:21:06
【问题描述】:

我是 Node 新手。

我将一堆前端函数从我的库中移到了一个新的 Node.js 库中。

我知道你必须把它放在 module.exports = {

并且所有的函数都必须是这种格式: tempToFahrenheit:函数(tempInC){

我可以正常调用其他脚本中的函数,但函数相互调用时遇到问题:

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;

在此文本上方,您会看到一行尝试在函数 getTextWeatherUsingStationUsingRequest() 中调用 tempToFahrenheit()。我该如何做到这一点?您必须为 Node.js 设置函数的奇怪方式(哈希对吗?)这些函数似乎无法相互访问。

另一个更一般的问题。 Node.js 的好处应该是您在前端和后端使用 Javascript,并且您可以重用代码,就像在库中一样。但正如我们在这里看到的那样,我必须对代码进行相当大的(并且容易出错)更改才能使其与 Node.js 一起使用。另外,我必须保留该库的两份副本,一份是前端,另一份是 Node.js。在 Node 中做库没有更好的方法吗?

【问题讨论】:

  • 你是在一个对象中声明这些函数吗? { tempToFahrenheit: ..., otherfunction : ..}?
  • @GeorgeBailey 是 module.exports = { tempToFahrenheit: ..., otherfunction : ..}

标签: javascript node.js


【解决方案1】:

在 Node 库中,所有函数都是公共对象 (modules.exports) 的成员。因此,当您想从另一个函数调用一个函数时,您必须指定您正在调用this.someFunction,而不仅仅是someFunction(后者将寻找一个全局可访问的someFunction,它并不存在)。

不过,如果您要在您的情况下尝试这样做,那么事情会更复杂一点,this 将引用不正确的上下文,因为该调用嵌套在几个异步回调中(req.onres.on) .因此,您会遇到同样的问题。

要解决此问题,请尝试在 getTextWeatherUsingStationUsingRequest 函数的开头添加 var self=this;,然后将 tempToFahrenheit 函数调用更改为 self.tempToFahrenheit

(变量self 将通过名为closure 的功能在回调中正确传播。this 不会这样做,因为它是始终引用当前上下文的保留关键字。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 2010-10-13
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多