我最近選擇了Node,發現事情並不總是按順序運行。我很困惑,我已經習慣了在Javascript中使用回調處理變量賦值?
1) Assignment
2) Print data
目前我正在下面的函數和調用var x = searchForProfessor("prof_name_here");
然後我打電話console.log(x);
只拿到不確定的。
我一直在閱讀關於遍歷整個網絡的回調,我無法將我的頭圍繞這個想法並將其應用於此代碼。有人可以給我一些直覺,以回調做出上述可能嗎?
我的功能
var searchForProfessor = function searchForProfessor(teacher_name) {
google.resultsPerPage = 10
var nextCounter = 0
google(teacher_name, function (err, res){
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")) {
request(link, function(err, resp, body){
if (!err && resp.statusCode == 200) { //If no error is going to happen, then print the data
var $ = cheerio.load(body); //Grab the body of data from 'prof_link'
var overall_rating = $('.breakdown-header .grade').text(); //Get the grade rating from the following classifications text
if (overall_rating.substr(0,3)) {
teacher_results.push(prof_name);
} //End if
} //End if
}); //End request
}//End if for comparisons ||
} //End For
}); //End google function
} //End searchForProfessor