出於某種原因,我在下面寫的代碼(我正在製作的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和調用函數的新手,爲什麼我的代碼不按照我的意圖執行?
'createTable'調用是異步的,所以當你console.log消息時,回調還沒有執行。 – 2014-09-01 04:20:09