0

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;
        }
    });
}
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • Hi there. Look into how async, including Promises, work. – Fissure King Jul 16 '18 at 14:53
  • The duplicate link will show you why this happens, and explains how to fix. To save you some time though, `newsapi.v2.everything(` place a return in front of this.. `return newsapi.v2.everything(`, and then call like -> `queryToSlack('Bitcoin', 3).then(function (bitcoinNews ) { /*code here*/});` – Keith Jul 16 '18 at 14:56

0 Answers0