我是JS的新手,我使用Google的新闻API创建了此函数,以返回格式为“ S”的查询“ 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;
}
});
}