1

I am trying to return a number that is retrieved through a couple of callback functions, but cannot for the life of me figure out why the scope isn't working. The goal is to return a value that is only accessible inside two additional layers of functions:

function getLastPosition(db) {
  var highest; // Declared in method's scope

  db.transaction(function (tx) {
    tx.executeSql('SELECT max(position) AS highest FROM FRUIT', [], function(tx, result) {
      highest = result.rows.item(0).highest;
      alert(highest); // Displays the number 2, as it should.
    });
  });

  alert(highest); // Displays 'undefined'!
  return highest;
}

I've read Ryan Morr's guide and still come up clueless...

EDIT: So it turns out not to be a problem of scope, but of asynchronous execution. The return statement is executing before the database call is done. My revised question, then, is how to get the value of highest without resorting to more callbacks.

Richard Pressler
  • 494
  • 3
  • 11
  • Is that closure function a callback? I'm thinking what maybe happens is that `return highest` is actually executing before you assign highest. Your SQL went off into being executed and the closure function hasn't been called from it finishing yet. Maybe? – SlaterCodes Feb 05 '16 at 23:26

1 Answers1

0

Do not know your library, but db suggests that you are making an asynchronous ajax call to a database. Because it is asynchronous, a request to the server is made and execution continues to the next line where highest is not yet defined. Later when the browser receives the response from the ajax call, the callback functions are executed and the value of highest is set.

Instead of returning highest, you could pass a callback function to your function and call it with the value of highest replacing your first alert.

function getLastPosition(db, callback) {
  var highest;
  db.transaction(function (tx) {
    tx.executeSql('SELECT max(position) AS highest FROM FRUIT', [], function(tx, result) {
      highest = result.rows.item(0).highest;
      callback(highest);
   });
 });  }