node.js - How should I organize my code? What I got now isn't reliable

时间:2017-04-10 01:00:44

标签: javascript node.js npm discord npm-request

I get an issue where some code writes to the console late or in random order, where did I go wrong?

var request = require('request');
var vFind = 'HelloWorld';
var vFound = false;
var vSites = ['http://www.youtube.com','http://www.gmail.com','http://www.apple.com','http://www.live.com','http://www.msn.com','http://www.yahoo.com','http://www.bing.com','http://www.purple.com','http://www.abc.xyz','http://www.reddit.com','http://www.stackoverflow.com','http://www.newgrounds.com','http://www.twitter.com','http://www.flickr.com','http://www.paypal.com','http://www.mediafire.com','http://www.mega.co.nz','http://www.soundcloud.com','http://www.slack.com','http://www.discordapp.com','http://www.trello.com','http://www.ninite.com','http://www.imgur.com','http://www.interacts.js','http://www.drive.google.com'];

  for (j = 0; j < (vSites.length); j++){
    request(vSites[j], function (error, response, vBody) {
      for (i = 0; i < (vBody.length); i++){
        if (vBody.substr(i,vFind.length) == vFind && vFound == false){
          vFound = true;
          break;
        }
      }
      if (vFound == false)
        console.log(vSites[j]+" didn't have it...");
      else if (vFound == true){
        console.log(vSites[j]+" has it!");
        vFound = false;
      }
    });
  }

1 个答案:

答案 0 :(得分:1)

Here is the pseudo code for what you have done:

For each website in vSites, make an HTTP request. Once the request is complete, run this function:

function (error, response, vBody) {
  for (i = 0; i < (vBody.length); i++){
    if (vBody.substr(i,vFind.length) == vFind && vFound == false){
      vFound = true;
      break;
    }
  }
  if (vFound == false)
    console.log(vSites[j]+" didn't have it...");
  else if (vFound == true){
    console.log(vSites[j]+" has it!");
    vFound = false;
  }
 }

What happens is: all the request are made and then when the response arrives at the client, the above function is called. Google may return a response quicker than YouTube and so on... You should look into Promises if you want to keep these in order.