-1

I'm trying to learn node.js and currently I'm just trying to print stuff out to the response. I am getting team roster from an NHL api and i can console.log it and i get the data. But when i try to call the function to the response.write that very variable is empty.

Here is the tutorial.js. And it's the gt.getTeam(team) that returns an empty string (from the variable 'players' from 'my_hockey_team.js' as seen below).

var http = require("http");
var gt = require("./my_hockey_team");
let team = process.argv.slice(2);

console.log(team[0]);

http.createServer(function (request, response){
  response.writeHead(200, {'Content-Type': 'text/html'});
  response.write("Players are"  + gt.getTeam(team[0]));
  console.log(gt.getTeam(team[0]));
  response.end("Hello World");
}).listen(3000);
console.log("Server running at 127.0.0.1");

process.on('uncaughtException', function (err) {
    console.log(err);
});

And here is the my_hockey_team.js. Inside the getTeam function the 'players'-variable never gets populated. I don't know if it's asynchronous thing or a scope thing or what it is.

const https = require ('https');
var http = require("http");

function getTeam(teamNr){
  let players = "";
  const request = https.get(`https://statsapi.web.nhl.com/api/v1/teams/${teamNr}/roster`, response => {
    let body = "";
    if (response.statusCode !== 200){
      request.abort();
    }
    response.on('data', data => {
      body += data;
    });

    response.on('end', () => {
      if (response.statusCode === 200){
        try {
          const team = JSON.parse(body);
          for (var i in team.roster){
            players += team.roster[i].person.fullName;
          }
        } catch(error) {
          console.log(error.message);
        }
      }
    });
  });
  request.on('error', error => {
    console.error(error.message + "Nåt gick fel med lagen?");
  });

  return players;
}

module.exports.getTeam = getTeam;

If i uncomment the console.log inside the respons.on('end..) i get all the data that i want but the 'players'-variable is just an empty string when i call the getTeam-function. Can someone please tell me what i'm doing wrong. Thanks!

dmfay
  • 2,417
  • 1
  • 11
  • 22
zeitmeister
  • 23
  • 1
  • 8

1 Answers1

0

getTeam needs to be an async function, return a promise, or (if you're using a really old version of Node) take a callback, and then your calling code needs to handle that appropriately. Right now the method looks like it's setting up all the asynchronous response handling correctly and then returning players as initialized before any of it can actually happen.

dmfay
  • 2,417
  • 1
  • 11
  • 22
  • Okey, i've been trying to read about promises but not sure how to implement it in my code. Do i wrap the whole `getTeam` function in a promise or specific part of the function? – zeitmeister Sep 19 '18 at 15:47