I'm new to JS and I created this function using Google's news API to return a string of the top 'n' articles on a query 'q' formatted to be sent to Slack.
When I console.log the variable "articles", it returns successfully with a string, but when I call the function (ex. bitcoinNews = queryToSlack('Bitcoin', 3) ), it returns undefined.
Seems like a scope problem? Any ideas?
function queryToSlack(q, n) {
//logic to get weekAgo and today
newsapi.v2.everything({
q: q,
from: weekAgo,
to: today,
language: 'en',
sortBy: 'popularity',
page: 1
}).then(response => {
if (response.articles[0].title) {
console.log(response.totalResults + " articles found");
var articles = '<' + response.articles[0].url + '|*' + response.articles[0].title + '*>\n*' +
response.articles[0].source.name + '*\n' + response.articles[0].description + '\n';
var i = 1;
while (i < n) {
articles = articles + '<' + response.articles[i].url + '|*' + response.articles[i].title + '*>\n*' +
response.articles[i].source.name + '*\n' + response.articles[i].description + '\n';
i++;
}
//this successfully returns n articles
console.log(articles);
//returns undefined
return articles;
} else {
console.log('No articles found');
var noArticles = 'No articles on ' + q + ' found this week';
return noArticles;
}
});
}