【发布时间】:2016-09-10 08:04:25
【问题描述】:
我最近拿起了 Node,发现事情并不总是按顺序运行。我很困惑,因为我已经习惯了
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
【问题讨论】:
标签: javascript asynchronous callback