2014-09-01 132 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

消除了我的猜測 - 錯過了關於正在執行的回調的觀點 - 這很可能是其他回覆提供的異步問題。