-1

I am new to JavaScript. I don't get it why it prints the value undefined on the console before the correct id.

I am trying to return the inserted id yet I get an "undefined" on the return, but the console shows the correct id.

VisaFam.dbs.addFamily = function(nom) {
    var db = VisaFam.dbs.db;
    var  family_id;

    db.transaction(function(tx) {


        tx.executeSql("INSERT INTO family (nom) VALUES (?)",
            [nom],function(tx, results){
                family_id= results.insertId;     //i want to return this 
                console.log(results.insertId);   // this prints the correct value 

             });
     });


    console.log(family_id); // this shows undefined
     return family_id; // the return is thus "undefined"

     }
isherwood
  • 58,414
  • 16
  • 114
  • 157
A.Mahamedi
  • 353
  • 1
  • 2
  • 11

2 Answers2

1

I don't have the full context of your program, but it seems that the db.transaction function is asynchronous. Because of this, the console.log() statement is running before the family_id variable has a value assigned to it.

To test this, you can change the line var family_id; to var family_id = "test"; Console should spit out "test" immediately.

To log the correct id you want, you need to move the console.log() call into the db.transaction function, which ensures the code will only execute after the value is set.

1

I/O calls happens async in js and you should get returned value either from callbacks or promises:

VisaFam.dbs.addFamily = function(nom, callback) {
    var db = VisaFam.dbs.db;
    var  family_id;

    db.transaction(function(tx) {
        tx.executeSql("INSERT INTO family (nom) VALUES (?)",
            [nom],function(tx, results){
                family_id= results.insertId;     //i want to return this 
                console.log(results.insertId);   // this prints the correct value 
                callback(results);
             });
        });
}

then call addFamily as:

addFamily(nom, function(response) {
    //handle response
})
guijob
  • 4,413
  • 3
  • 20
  • 39