简体   繁体   中英

how to set a variable inside of a callback function in JavaScript?

i am testing Phonegap Web Storage for a small project:

var listsCount = 0;

tx.executeSql("SELECT * FROM list WHERE id = ?", [id], successGetList, errorGetList );

function successGetList(tx, results){
    listsCount = results.rows.length; // this will be 2, in my case
}

function errorGetList(err){
    console.log("Error processing SQL: "+err.code);
}

console.log(listsCount); // this will show 0, instead of 2

the issue i'm having is that listsCount doesn't get set inside the successGetList method. Even if i return it there.

any ideas on how can i set that variable inside of successGetList function ?

thanks

It does get set, but your console.log call is being fired before that (that's how asynchronous code works!). Just use the value from the callback. If you need, call another function from there, and pass your data to it.

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