javascript - 即使其中的代码被激活,if 语句也不会阻止事件流
问题描述
我的代码中的“if 语句”继续执行 console.log,它位于“if 语句”之后,即使其中的代码正在调用搜索函数。
有什么办法可以防止这种情况吗?
function search() {
/**
* The Tweet checking algorithm.
* @private
*/
function checkTweet(tweet) {
if (tweet.favorite_count <= 5) {
log('less than 5 likes');
search();
}
if (getBlockedWords().includes(tweet.text)) {
log('includes blocked words');
search();
}
console.log(tweet); // This line activates even though the if statements are calling the search function.
}
Twitter.get(
'search/tweets',
{q: getSearchKey(), count: 30, lang: 'en'},
function(err, data, response) {
let tweetList = [];
if (!err) {
for (let i = 0; i < data.statuses.length; i++) {
let tweet = data.statuses[i];
tweetList.push(tweet);
}
var result = tweetList[Math.floor(Math.random() * tweetList.length)];
checkTweet(result);
} else {
log(err);
sleep(search);
}
});
}
解决方案
if 语句不一定会停止代码流。如果条件评估为真,则运行if语句。是否继续运行取决于 if 语句中的代码。
实现此目的的一种简单方法是return
在 if 块中简单地使用。这将阻止该函数中的其余代码运行。
function checkTweet(tweet) {
if (tweet.favorite_count <= 5) {
log('less than 5 likes');
search();
return;
}
if (getBlockedWords().includes(tweet.text)) {
log('includes blocked words');
search();
return;
}
console.log(tweet); // This line activates even though the if statements are calling the search function.
}
推荐阅读
- javascript - 在我 json_encode() 我的 php 数组之后我该怎么办?
- c - C程序导致内存泄漏?
- php - PHP无法解码ASCII字符
- android - 如何在活动之间传递从内部存储中选择的 ImageView
- ruby - 在 Ruby 程序中出现未初始化的常量错误 - 为什么我不能格式化数字?
- rabbitmq - spring-cloud-stream 兔子活页夹未分区目的地
- c# - 如何分组然后透视数据
- sql - 是否有一个sql查询可以统计特定年份的人数,知道每个人的出生日期和死亡日期?
- javascript - SVG图标上的Onlick可以是路径或svg,如何只制作SVG?
- oop - “严格继承”的例子