【发布时间】:2017-01-20 04:15:08
【问题描述】:
我有以下功能:
function filterDesiredURLs(tweet) {
tweet.entities.urls.forEach((url) => {
desiredURLs.forEach((regexPattern) => {
if (regexPattern.test(url['expanded_url'])) {
console.log('hello, im returning');
return true;
}
})
})
}
我这样称呼它:
console.log(filterDesiredURLs(tweet));
其中 tweet 是一个已定义的对象。我可以看到该函数确实正在返回,因为我在控制台中看到了输出 hello, im returning,但 console.log(filterDesiredURLs(tweet));prints undefined。我希望匿名函数作为异步操作的回调传递,但这不是异步的,所以返回应该有效。发生了什么事?
【问题讨论】:
-
您是从内部函数返回的,而不是外部函数。
Array#forEach忽略其回调的返回值。 -
看起来您的代码应该使用
Array#filter和Array#some而不是两个forEach循环。
标签: javascript asynchronous return anonymous-function