3
\$\begingroup\$

I'm new to JavaScript and was hoping there was a cleaner way to write this. It's a block of code that looks at a group of documents in a collection (called Messages), and makes a call to the GitHub API for each one. If any of the API calls finds a certain string in the response, the function returns true via callback. If all of the API calls are exhausted without finding the string, the function returns false. The only way I could really think to do this was with the async module, which feels like a dirty/ugly solution. I was hoping someone here might be able to show me if/how this could be possible without the async module.

function isUserBlacklisted(user, topCallback){
  // Grab each alert we've sent to that user,
  // see if any of their comments are 'STOP'
  var isBlacklisted = false;
  Messages.find({ user: user }).toArray(function(err, messages){
    async.eachSeries(messages, function(message, callback){
      if (isBlacklisted){
        // eachSeries checks each one. This short-circuits the call so we don't
        // waste API calls if we find out the user is blacklisted halfway
        // through the list.
        callback(); 
      }
      else{
        var options = {
          user: message.user,
          repo: message.repo,
          number: message.number
        }
        github.issues.getComments(options, function(err,obj){
          console.log("Made a call to github for issue #" + message.number);
          if(isStopInComments(obj)){
            Messages.update(options, {$set:{isBlacklisted: true}});
            isBlacklisted = true;
          }
          callback();
        });
      }
    },
    function(err){ topCallback(isBlacklisted)});
  });
}
\$\endgroup\$
  • \$\begingroup\$ It doesn't look to me like this code would even work. isBlackListed won't be set yet when you try to return it as the return value from isUserBlackListed() because it's value comes from async operations that won't complete until later. \$\endgroup\$ – jfriend00 Feb 1 '15 at 4:46
  • \$\begingroup\$ Woops, i forgot to take that last bit out of there. The whole thing works as a callback by calling topCallback once async completes. \$\endgroup\$ – Grant David Bachman Feb 1 '15 at 4:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.