2013-02-18 65 views
1

我是一个小项目测试Phonegap Web Storage如何在JavaScript中设置一个回调函数中的变量?

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 

我遇到的问题是listsCount不会被设置successGetList方法内。即使我回到那里。

关于如何在successGetList函数中设置该变量的任何想法?

感谢

+0

[如何从函数返回AJAX调用的响应?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-函数调用)(当然,这不是AJAX,但同样的异步行为适用。) – 2013-02-18 18:54:37

+0

@FrédéricHamidi这也不是关于'return'的问题。你说得对,那里的答案应该指出正确的方向,但是对于这个特定的问题来说可能太多了。 – bfavaretto 2013-02-18 19:00:30

回答

4

它得到的设置,但在此之前你console.log呼叫被解雇(这是代码的异步工作!)。只需使用回调中的值即可。如果需要,请从那里调用另一个函数,并将数据传递给它。

+0

'只需使用回调函数的值,怎么样? – Patrioticcow 2013-02-18 19:15:00

+0

我的意思是从'successGetList'中使用'results.rows.length',或者从那里调用另一个函数并传递它。确切的答案将取决于你想要做什么的值... – bfavaretto 2013-02-18 19:15:56

+0

明白了。没有注意到回调是异步的。谢谢 – Patrioticcow 2013-02-18 19:17:08

相关问题