即使没有正确的设置变量,脚本如何继续?谢谢你的回复!
代码
function get(param) {
// Connect to database and get the response ~ 1 sec
db.get(param, function(output) {
console.log("Hey, I set the variable!");
return output;
});
}
try {
var username = get("username");
var birthday = get("birthday");
} catch (e) {
error = e;
}
if ( !error ) {
console.log("No errors? Everything all right?");
}
输出
No errors? Everything all right?
Hey, I set the variable!
答案 0 :(得分:1)
你在想同步。发生了什么是调用了两个get
语句,但db
尚未调用任何回调。你的程序继续快速检查error
是否未定义,因为从未输入catch块。结果,打印出“无错误......”。然后db
在退出之前异步响应您的get
个电话之一。这里的关键是你不能假设print语句是username
回调的结果,它可能来自birthday
。
答案 1 :(得分:0)
虽然我不知道它是什么数据库代码,但可以肯定的是,传递给db.get()
的函数无法按照代码所需的方式工作。该函数是一个回调,在数据库结果“准备好”之前不会被调用。你不能有一个“get()”例程,它的工作方式与你的方式相同,换句话说,因为它不能“等待”db.get()
调用。
您可以重写“get()”函数以获取自己的函数参数。