【发布时间】:2012-12-02 22:18:36
【问题描述】:
我刚刚涉足了服务器端 javascript 的美妙世界,并且仍在学习异步处理的窍门。在搞砸了一个节点项目之后,我意识到这个 javascript 就像我过去的很多女朋友一样——他们只是不会回调。无论如何,我希望有人可以帮助我......这是代码,下面有解释:
//this is the function I'm calling to
function queryDb(connection, sql){
connect(connection, function(){
connection.query(sql, function(err, results){
if(!err){
return results;
end(connection);
}
else{
throw err;
}
});
});
}
这是我打电话的地方。调用后我希望执行一些代码,但要等到这个函数完成处理(它实际上是对数据库的查询,所以需要更长的时间,我的 js 会继续运行)。
var queryResults = db.queryDb(db.connection, "SELECT * FROM Clients");
if(queryResults){
console.log(queryResults);
req.dbResults = queryResults;
next();
}
else{
console.log('The query results where not returned here is the queryResults variable: ' + queryResults);
}
我希望发生的是从父函数返回的结果,然后由子函数运行的回调对结果进行处理。我试过这个:
queryDb(db.connection, "SELECT * FROM Clients", function(){
if(results){
console.log(results);
req.dbResults = results;
next();
}
else{
console.log('The query results where not returned here is the queryResults variable: ' + results);
}
});
但是我无法在“调用函数”的回调中访问父函数返回的结果。
【问题讨论】:
-
为你的 livejournal 保存令人沮丧的 cmets。
-
从异步回调中返回是没有用的(也许这也可以作为关系建议)。
-
只是有一点乐趣:)
标签: javascript node.js asynchronous callback