0

Hello guys im working on a new project with js and i have a problem so i would like to know how do i change variable in anonymous functions

myFunct : function(){

    var name = "Alexander ";

    if(true)
    {

        db.transaction(function(t){

            name = "Stephane"; //How do i change my variable [name] at this level?

            t.executeSql('SELECT * FROM users',[]);
        });
    }

    return name; //this function returns me Alexander and not Stephane
},
  • #unclearwhatyoureasking happy thanksgiving – Rooster Nov 26 '15 at 06:30
  • 1
    this is called closures. name is captured inside function and does not change outside variable. – Access Denied Nov 26 '15 at 06:32
  • Guessing here, if you want "Alexander" inside your db.transaction, pass it (function(t,name){}); – Jules Nov 26 '15 at 06:34
  • 2
    @AccessDenied: No, it's not. Yes, it's a closure, and *that's why* the function can change the outside variable. – Bergi Nov 26 '15 at 06:35
  • Your anonymous function works fine. It *does* change the variable - only it is too late. Being invoked asynchronously, the old value has already been `return`ed before the assignment happens – Bergi Nov 26 '15 at 06:36

1 Answers1

0

The callback function for db.transact runs after the function has returned.

If you put a console.log above the line where you change the name, and one above when you return, then you'll see this.

If you want to return the name as a value, consider instead returning a Promise, then resolving the promise with the name as a value.

Alternatively, your function could accept a callback, which will be called with the value, after the transaction has finished.

Dan Prince
  • 29,491
  • 13
  • 89
  • 120