Reputation: 79
i have written code to get max data from database and then insert that data in another table but it is not giving data first time.it is giving leadid as undefined because it is not waiting result of getMaxLeadId and executing second statement.my code is given below
var leadId = getMaxLeadId();
alert("leadId"+leadId);
function getMaxLeadId() {}
and
function getMaxIdData_success(tx, result){}
after I need to call insert maxLeadId
into insert function.
Please suggest me some idea how to write callback function in java Script.
Upvotes: 0
Views: 315
Reputation: 457
The common way to do this is with callbacks in a style of programming known as CPS.
The general form of this is
var doSomeCalc = function(resultFunc) {
//do some long running calc
var result = 4;
resultFunc(result);
};
var writeOutResult = function(result) {
console.log(result);
};
doSomeCalc(writeOutResult);
so you will want to write your getMaxLeadId() in this form to take the callback then should be called when it has calculated the answer.
Don't forget to mark this as the correct answer if you think it is.
Upvotes: 3