首页 > 解决方案 > 带有 API 调用的 Node.Js 函数返回未定义

问题描述

我是 JS 新手,我使用 Google 的新闻 API 创建了这个函数,以返回格式为发送到 Slack 的查询 'q' 上的前 'n' 篇文章的字符串。

当我 console.log 变量“articles”时,它使用字符串成功返回,但是当我调用该函数(例如 bitcoinNews = queryToSlack('Bitcoin', 3) )时,它返回未定义。

似乎是范围问题?有任何想法吗?

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;
        }
    });
}

标签: javascriptnode.js

解决方案


推荐阅读