1

File called testing.js

I can do whatever I like with the data in saveWeatherData but cannot call this function and return the data without getting 'undefined' For example if i tried the below code in saveWeatherData it will print out the summary as expected... console.log(The summary of the weather today is: ${dataArray[0]});

However I want to use these values within another file such as a server file that when connected to will display weather summary temperature etc. So I need to return an array with these values in it so that I can call this function and get my data stored in an array for further use.

I know that the reason the array --dataArray is returning undefined is because asynchronous code. The array is returned before we have gotten the data using the callback.

My question, is there anyway to do what I am trying to do? I tried my best to explain the problem and what I want to do, hopefully its understandable.

Would I have to use a callback inside of a callback? To callback here to return the data when its been fetched? I just cant get my head about it and have tried multiple things to try and get the result I am looking for.

My last idea and something i would prefer not to do is the use the 'fs' module to save the data to a text or json file for use in my other files through reading the data from the saved file...

I feel im close but cant get over the last hurdle, so ive decided to ask for a little help, even just point me on the right track and Ill continue to try and figure it out. Phew...

Thank you for your time!

const request = require("request");

let dataArray = [];

let saveWeatherData = function(weatherData) {
    dataArray = weatherData;
    return dataArray;
};

let getWeatherData = function(callback) {

    request({
        url: `https://api.forecast.io/forecast/someexamplekey/1,-1`,
        json: true
    }, (error, response, body) => {

        //Creating array to hold weather data until we can save it using callback...
        let array = [];
        if (error) {
            console.log("Unable to connect with Dark Sky API servers.")
        }
        else {
            console.log(`Successfully connected to Dark Sky API servers!\n`);

            array.push(body.currently.summary, body.currently.temperature, body.currently.apparentTemperature, body.currently.windSpeed, body.currently.windBearing);

            callback(array);
        }
    });
};

getWeatherData(saveWeatherData);

module.exports = {
    saveWeatherData
};

My Other File... File called server.js

const http = require("http");

const testing = require("./testing");

function onRequest(request, response){
    let data = testing.saveWeatherData();

    console.log(`A user made a request: ${request.url}`);

    response.writeHead(200, {"context-type": "text/plain"});

    response.write("<!DOCTYPE html>");
    response.write("<html>");
    response.write("<head>");
    response.write("<title>Weather</title>");
    response.write("</head>");
    response.write("<body>");
    response.write("Weather summary for today: " + data[0]);
    response.write("</body>");
    response.write("</html>");

    response.end();
}

http.createServer(onRequest).listen(8888);
console.log("Server is now running on port 8888...");
1
  • 2
    No, saveWeatherData cannot work. You will need to export getWeatherData, and then you need to pass the code that uses data as a callback. Commented Jul 27, 2018 at 16:32

1 Answer 1

1

I'm still not sure about what are you trying to do. However, I think you're not exporting what you suppose to be exporting. To avoid the use of so many callbacks you may use async/await.

Change this part of your server.js

async function onRequest(request, response) {
  let data = await testing.getWeatherData();

  console.log(`A user made a request: ${request.url}`);

  response.writeHead(200, { 'context-type': 'text/plain' });

  response.write('<!DOCTYPE html>');
  response.write('<html>');
  response.write('<head>');
  response.write('<title>Weather</title>');
  response.write('</head>');
  response.write('<body>');
  response.write('Weather summary for today: ' + data[0]);
  response.write('</body>');
  response.write('</html>');

  response.end();
}

And this of your testing.

let getWeatherData = function() {
  return new Promise(resolve =>
    request(
      {
        url: `https://api.darksky.net/forecast/someexamplekey/1,-1`,
        json: true
      },
      (error, response, body) => {
        //Creating array to hold weather data until we can save it using callback...
        let array = [];
        if (error) {
          console.log('Unable to connect with Dark Sky API servers.');
        } else {
          console.log(`Successfully connected to Dark Sky API servers!\n`);
          array.push(
            body.currently.summary,
            body.currently.temperature,
            body.currently.apparentTemperature,
            body.currently.windSpeed,
            body.currently.windBearing
          );
          resolve(array);
        }
      }
    )
  );
};

module.exports = {
  getWeatherData
};

It will check for new Weather in each request. If you want to save the result to avoid checking every single time you might need to do something else. But I think for a weather app the important is to keep it updated.

Sign up to request clarification or add additional context in comments.

6 Comments

Why are you declaring getWeatherData() as async. You are not using await and I don't see any other reason that it is async. Just make it a regular function that returns a promise. And, you can just use the request-promise module that promisifies request() for you so you don't have to do that manually.
I had no intention about that async. But I assume he gets the point, right?
I was attempting to give you feedback on how you could improve your answer. You can edit your answer to remove the async on getWeatherData() since it is not needed and you can improve your answer by showing them how to use request-promise which will be simpler than what you currently show.
Thank you while I don't fully grasp how this works i'm going to give it a shot, all I needed was someone to point me in a new direction, im sure i can I can figure this out... thank you for your time...
This worked perfectly thank you so much, I understand nearly all of it too. Just have to play around with it bit more and watch some other videos on es6 promises and the use of the aysnc keyword. I kind of understand that part the async but have to look up a bit more and practice, and once again much thanks.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.