Javascript代码没有同步执行?

时间:2016-05-13 19:35:52

标签: javascript asynchronous

我在Node中构建我的第一个应用程序,看到代码没有按顺序执行。

我希望teach_name = parseProfessorData(link.href, link.title);在它下面的if块之前执行。我有没有办法对此进行编码以使其成为可能?

SearchForProfessor

var searchForProfessor = function(teacher_name) {



  google.resultsPerPage = 10
  var nextCounter = 0

  google(teacher_name, function (err, res){
    if (err) console.error(err)

    for (var i = 0; i < res.links.length; ++i) {
      var link = res.links[i];
      if (link.title.includes('Add') || link.title.includes('RATINGS') || link.title.includes("Hint")) {
        // Do not include these results
      }
      else {
        teach_name = parseProfessorData(link.href, link.title);

        if (teach_name != undefined){
          teacher_results.push(teach_name);
          console.log("sent!");
          console.log(teach_name);
        }

      }
    }
    //Return the array of the professor data here!!
  });
}

parseProfessorData

var parseProfessorData = function(prof_link, prof_name) {


  request(prof_link, function(err, resp, body){

    //If no error is going to happen, then print the data
    if (!err && resp.statusCode == 200) {

      //Grab the body of data from 'prof_link'
      var $ = cheerio.load(body);

      //Get the grade rating from the following classifications text
      var overall_rating = $('.breakdown-header .grade').text();

      //Print the prof results and ratings
      if (overall_rating.substr(0,3)) {

        //Log the data to console & push to mongo object & array
        console.log("loaded for " + prof_name);
        console.log("User Rating: " + overall_rating.substr(0,3));
        console.log("append successfully!");
        return prof_name;
      }
    }

    //When there is an error
    else {
      console.log("errored");
      console.log(err);
    }
  });

}

0 个答案:

没有答案