1

I'm trying to store the return value of a function into a variable but it doesn't seem to work. I have tried everything I could possibly think about.. Maybe I'm just doing something really stupid :D I'm running the code in NodeJS using express, request, body-parser and mongoose.

var requestNews = function(){
    request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){
    if (!error && response.statusCode == 200){
        var parsedData = JSON.parse(body);
        var title       =  parsedData.articles[randomNum].title;
        var description =  parsedData.articles[randomNum].description;
        var url         =  parsedData.articles[randomNum].url;
        var urlToImage  =  parsedData.articles[randomNum].urlToImage;
        var publishedAt =  parsedData.articles[randomNum].publishedAt;
        var articleObj  = {
            title: title, 
            description: description, 
            url: url, 
            urlToImage: urlToImage, 
            publishedAt: publishedAt

        };
        articleObjStr = JSON.stringify(articleObj);
        return articleObjStr;
    }
});
};


app.get("/index", function(req, res){
    var randomNew = requestNews();
    console.log(randomNew); // LOGS UNDEFINED
    res.render("index", {randomNew: randomNew});
});

Anyone any ideas?

Thanks for the help!

3
  • Are you sure the api is returning 200 and all of the data you're requesting? Commented Jul 13, 2017 at 15:09
  • requestNews is an asynchronous function. It does not return a value, but should accept a callback as a parameter, that is called with the articleObjStr once the request's response is received. Commented Jul 13, 2017 at 15:10
  • The API is working, there is no error. :) Thanks for the help. I started coding a couple of months ago and I still have a steep path ahead of me. Commented Jul 13, 2017 at 15:24

5 Answers 5

4

request is async operation and you can not assign value like that. You can use callback or promise.

Here is a snippet code on how can you achieve this using callbacks

var requestNews = function(callback){
  request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){
    if (!error && response.statusCode == 200){
      var parsedData = JSON.parse(body);
      var title       =  parsedData.articles[randomNum].title;
      var description =  parsedData.articles[randomNum].description;
      var url         =  parsedData.articles[randomNum].url;
      var urlToImage  =  parsedData.articles[randomNum].urlToImage;
      var publishedAt =  parsedData.articles[randomNum].publishedAt;
      var articleObj  = {
        title: title, 
        description: description, 
        url: url, 
        urlToImage: urlToImage, 
        publishedAt: publishedAt

      };
      articleObjStr = JSON.stringify(articleObj);
      callback(null, articleObjStr);
    } else {
      callback(error)
    }
  });
};


app.get("/index", function(req, res, next){
  requestNews(function(err, data) {
    if (err) return next(err);
    console.log(data);
    res.render("index", {randomNew: data});
  });

});

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

Comments

2

Use a callback :

var requestNews = function(callback){
    request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){
    if (!error && response.statusCode == 200){
        var parsedData = JSON.parse(body);
        var title       =  parsedData.articles[randomNum].title;
        var description =  parsedData.articles[randomNum].description;
        var url         =  parsedData.articles[randomNum].url;
        var urlToImage  =  parsedData.articles[randomNum].urlToImage;
        var publishedAt =  parsedData.articles[randomNum].publishedAt;
        var articleObj  = {
            title: title, 
            description: description, 
            url: url, 
            urlToImage: urlToImage, 
            publishedAt: publishedAt

        };
        articleObjStr = JSON.stringify(articleObj);
        return callback(null, articleObjStr);
    } else {
      return callback(error);
    }
});
};


app.get("/index", function(req, res){
    requestNews(function(err, data){
      if(err) console.log(err);
      else {
        var randomNew = data;
        console.log(randomNew); // LOGS UNDEFINED
        res.render("index", {randomNew: randomNew});
      }
    });

});

Comments

1

You are trying to get the return value from an asynchronous method, which is not possible. In order to complete your action, you can do following:

app.get("/index", function(req, res){
     requestNews(req, res);
});

var requestNews = function(req, res){
request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){
if (!error && response.statusCode == 200){
    var parsedData = JSON.parse(body);
    var title       =  parsedData.articles[randomNum].title;
    var description =  parsedData.articles[randomNum].description;
    var url         =  parsedData.articles[randomNum].url;
    var urlToImage  =  parsedData.articles[randomNum].urlToImage;
    var publishedAt =  parsedData.articles[randomNum].publishedAt;
    var articleObj  = {
        title: title, 
        description: description, 
        url: url, 
        urlToImage: urlToImage, 
        publishedAt: publishedAt

    };
    articleObjStr = JSON.stringify(articleObj);
   // return articleObjStr; do not return value from here it can not be retrived
   res.render("index", {randomNew: articleObjStr});
   }
  });
};

Comments

0

requestNews function is not returning nothing.

var requestNews = function(){

      // Missing return Here.
      return request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){

      // All you code here.    
      return articleObjStr;
    }
  });
};

The problem is that you are retuning a value in the function that you pass to the request method, and if this is a call back, it also will not work.

If is a call back do it in this way:

var requestNews = function(onNewsRetrived){ // Use a callback here
          request("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=2cc11b1813c942*************", function(error, response, body){

      onNewsRetrived(articleObjStr); // Trigger your call back get you got the info.
    }
  });
};

app.get("/index", function(req, res){
   requestNews(funtion(randomNew) {

    console.log(randomNew); // Should Work
    res.render("index", {randomNew: randomNew});

   });       
});

Comments

0

Callback function is not triggered. That's the reason undefined value is getting printed in log.

Comments

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.