2014-09-01 128 views
0

出于某种原因,我在下面写的代码(我正在制作的POST路径)并不完全按照我的想法运行。Javascript回调函数错误

app.post("/", function (req, res, error) { 
    var message = ""; 
    tableSvc.createTable("tableName", function (error, result,response){ 
     if (error) 
     message += "There was an error in creating this table"; 
     else 
     message += "Table created succesfully"; 

    }); 
    console.log(message);  
}); 

不是打印"There was an error...""Table created..."的,上面只代码打印出一个空字符串。
我知道回调函数正在执行,因为如果我将console.log(message)置于回调函数内部,那么上面两个字符串中的任何一个都会打印到控制台。
我是Javascript和调用函数的新手,为什么我的代码不按照我的意图执行?

+0

'createTable'调用是异步的,所以当你console.log消息时,回调还没有执行。 – 2014-09-01 04:20:09

回答

0

我认为变量消息的范围是这里的问题。我没有尝试过,但可以工作。

app.post("/", function (req, res, error) { 
    var obj = this; 
    obj.message = ''; 
     tableSvc.createTable("tableName", function (error, result,response){ 
      if (error) 
      obj.message += "There was an error in creating this table"; 
      else 
      obj.message += "Table created succesfully"; 

     }); 

     while(obj.message.length===0){ 
      ;//Block the next execution till the operation above is complete. 
     } 


     console.log(obj.message);  
    }); 
+0

我认为,因为tableSvc.createTable是异步的,所以它可以在实际完成回调函数之前执行console.log(obj.message)。您应该移动回调函数本身的逻辑。或同步拨打电话。或者稍后使用setInterval,除非通过回调来更改变量(消息)值。 – Ganesh 2014-09-01 05:03:41

+0

是的,如果该方法是异步的,那么它也解释了我注意到的其他行为。接受的答案(更多为您的评论比回答:) – AmitS 2014-09-01 05:51:46

+0

我了解2/3的解决方案,但我怎么能同步进行调用,而不改变实际的方法本身? – AmitS 2014-09-01 05:53:17

0

消除了我的猜测 - 错过了关于正在执行的回调的观点 - 这很可能是其他回复提供的异步问题。