javascript - 带有 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;
}
});
}
解决方案
推荐阅读
- css - 样式 ShinyDashboardPlus 旋转木马 - 额外的矩形
- json - 如何使用 Kotlin 原生序列化避免不必要的命名?
- python - Python 运算符过滤器不起作用(Selenium)
- python - 将 ID 上的数据框的行组合起来以求和,但保留分类数据
- asp.net - ASPX 将字符串转换为布尔值
- python - 将字符串转换为元组
- scala - 为什么 Haskell 不需要蹦床?
- computer-vision - 为什么 grid_sample 函数将输入值限制为 [-1, 1]?
- python - 使用 python 重写 if-else 语句,如 javascript 对象文字
- windows-subsystem-for-linux - 剪贴板未在 wsl 和 windows 10 neovim 之间共享