2010-11-25 81 views
0

即使没有正确的设置变量,脚本如何继续运行?感谢您的回复!无回调设置变量

代码

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

我想有一堆你没有向我们展示的代码。 – Pointy 2010-11-25 21:56:55

回答

1

你在同步思考。发生的是两个get语句被调用,但db尚未调用任一回调。你的程序继续愉快地继续检查error,这是未定义的,因为catch块从未被输入。因此,打印出“没有错误......”。然后db在退出之前对您的get调用之一进行异步响应。这里的关键是你不能假设打印语句是username回调的结果,它可能是从birthday

0

虽然我不知道是什么数据库的代码是,它的功能,你传递给db.get()不能工作肯定的赌注你的代码似乎想要的方式。该函数是一个回调函数,在数据库结果“准备就绪”之前不会被调用。您不能有一个“get()”例程,它以您的方式工作,换句话说,因为它不能“等待”db.get()调用。

你可以重写你的“get()”函数来获取自己的函数参数。