I know the nature of Ajax is the asynchronous, thus my code is wrong. But I need help to find another solution.
Case is: I insert data into my database with:
self.insertTextItem = function (item) {
console.log("Insert TextItem with Service");
return $.ajax({
type: "POST",
url: serviceRoot + "InsertTextbatchTagItem",
beforeSend: serviceFramework.setModuleHeaders,
data: item,
cache: false
});
};
item.Id = null; // Id is autocreated in db.
item.Text = "Finally Friday!";
self.insertTextItem(item)
.done(function (newtext) {
item.textbatchId = newtext.Id;
}
//continuous code…
This works find in most cases. Exception is when I need the data returned from the database right away. However I need the "continuous code" to wait for the Id to be returned. The obvious solution is to place the "continuous code" into the callback-function, but as it is, I am calling self.insertTextItem in a function, thus the calling-function returns without waiting. (And obviously the callback function is ended within the calling function.)
How can I rewrite the self.insertTextItem-function in this case?