For some reason the code I wrote below(an POST route I was making) is not exactly working how I thought it would.
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);
});
Instead of printing "There was an error..."
or "Table created..."
, the code above only prints out an empty string.
I know that the call-back function is being executed because if I put console.log(message)
inside of the call-back function, then either of the above two strings does get printed to the console.
I am new to Javascript and call-functions, so why isn't my code executing the way I intended it to?
消除了我的猜测-错过了您关于执行回调的要点-这很可能是其他回复提供的异步问题。
I think the scope of variable message is the problem here. I have not tried this but may work.
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.