简体   繁体   中英

value is not returned from database

I'm trying to fetch a value from database like this

var batsmanId = getBatsmanid(localStorage.getItem('batsmanOne'));

Here is the method definition:

function getBatsmanid(name){
 var id;
 db.transaction(function(tx) {
      tx.executeSql('SELECT * FROM player where player_name = ?',[name], function(tx, results) {
       id = results.rows.item(0).player_id;
       console.log('Batsman ID: '+id);
      });
     });        
     return id;
}

While executing, the method is not returning id to the variable batsmanId , whereas the value is shown in console.

My feel is the database operation is taking time to execute .

Please share your thoughts.

Your feeling is correct.

In Javascript you cannot (shouldn't) "wait" for something to happen, and the model used is the opposite and more like "call me when you're done".

The function passed to executeSQL that is extracting the data will be called at a later time, and you should rework your interface around this approach (that is instead of just setting the variable id do the rest of the processing needed with that id once it arrives).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM