javascript - Accessing method variable from within layers of anonymous functions -
this question has answer here:
i trying return number retrieved through couple of callback functions, cannot life of me figure out why scope isn't working. goal return value accessible inside 2 additional layers of functions:
function getlastposition(db) { var highest; // declared in method's scope db.transaction(function (tx) { tx.executesql('select max(position) highest fruit', [], function(tx, result) { highest = result.rows.item(0).highest; alert(highest); // displays number 2, should. }); }); alert(highest); // displays 'undefined'! return highest; }
i've read ryan morr's guide , still come clueless...
edit: turns out not problem of scope, of asynchronous execution. return statement executing before database call done. revised question, then, how value of highest without resorting more callbacks.
do not know library, db suggests making asynchronous ajax call database. because asynchronous, request server made , execution continues next line highest not yet defined. later when browser receives response ajax call, callback functions executed , value of highest set.
instead of returning highest, pass callback function function , call value of highest replacing first alert.
function getlastposition(db, callback) { var highest; db.transaction(function (tx) { tx.executesql('select max(position) highest fruit', [], function(tx, result) { highest = result.rows.item(0).highest; callback(highest); }); }); }
Comments
Post a Comment