首页 > 解决方案 > 即使其中的代码被激活,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);
      }
  });
}

标签: javascriptnode.js

解决方案


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.
  }

推荐阅读