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!
requestNewsis an asynchronous function. It does not return a value, but should accept a callback as a parameter, that is called with thearticleObjStronce the request's response is received.