Patrioticcow
Patrioticcow

Reputation: 27048

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

Upvotes: 1

Views: 163

Answers (1)

bfavaretto
bfavaretto

Reputation: 71918

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.

Upvotes: 4

Related Questions