0

I'm trying to write a function that pulls data from the COVID-19 API. Here's my function:

function covidcases(){
  var http = require('follow-redirects').http;
  var fs = require('fs');
  
  var options = {
    'method': 'GET',
    'hostname': 'covidtracking.com',
    'path': '/api/us',
    'headers': {
    },
    'maxRedirects': 20
  };
  
  var req = http.request(options, function (res) {
    return new Promise((resolve, reject) => {
      var chunks = [];
  
      res.on("data", function (chunk) {
        chunks.push(chunk);
      });
    
      res.on("end", function (chunk) {
        var body = Buffer.concat(chunks);
        console.log("From the console.log: "+body.toString());
        resolve(body.toString());
      });
    
      res.on("error", function (error) {
        reject(error);
      });
    })
  });
  
  req.end();
  }
  module.exports = {covidcases}
  console.log(covidcases())

When ran in visual studio code, this is the result:

undefined
From The console.log: [{"date":20201011,"states":56,"positive":7727630,"negative":102250976,"pending":11261,"hospitalizedCurrently":34028,"hospitalizedCumulative":423058,"inIcuCurrently":6583,"inIcuCumulative":21553,"onVentilatorCurrently":1614,"onVentilatorCumulative":2454,"recovered":3075077,"dateChecked":"2020-10-11T00:00:00Z","death":206597,"hospitalized":423058,"totalTestResults":115424481,"lastModified":"2020-10-11T00:00:00Z","total":0,"posNeg":0,"deathIncrease":464,"hospitalizedIncrease":999,"negativeIncrease":800029,"positiveIncrease":46776,"totalTestResultsIncrease":943645,"hash":"deda38c4ef4e1ba880c187cc8f0b1e67f7822f36"}]

My guess is that the function isn't waiting for the Buffer.concat(chunks) to finish. How do I fix this?

Han75
  • 3
  • 1
  • 1
  • 3
  • 3
    `covidcases` seems to have no `return` statement. – Scott Sauyet Oct 12 '20 at 17:11
  • But you didn’t return anything from `covidcases()` of course `undefined` is expected. What’s your expecting return value? – hackape Oct 12 '20 at 17:12
  • @hackape I want it to return body.toString(), but if I put return body.toString() it is still undefined. – Han75 Oct 12 '20 at 17:12
  • You should return `req` and remember using `let` and `const` in most cases instead of `var`. Also, I would define required modules outside the function – Agustin Moles Oct 12 '20 at 17:15
  • You might want to look at this Q&A: https://stackoverflow.com/q/14220321. It seems like you want to make your asynchronous function synchronous. That can't happen, but with Promises or `async`-`await`, you might make it feel a bit more like that. – Scott Sauyet Oct 12 '20 at 17:15

0 Answers0