【问题标题】:how to set a variable inside of a callback function in JavaScript?如何在 JavaScript 的回调函数中设置变量?
【发布时间】:2013-02-18 18:52:32
【问题描述】:

我正在为一个小项目测试Phonegap Web Storage

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 函数中设置该变量的任何想法?

谢谢

【问题讨论】:

  • How to return the response from an AJAX call from a function? 的可能重复项(当然,这不是 AJAX,但同样的异步行为也适用。)
  • @FrédéricHamidi 这也不是在问return。你说得对,那里的答案应该指向正确的方向,但对于这个特定的问题来说,这可能太多了。

标签: javascript variables cordova callback web-storage


【解决方案1】:

它确实已设置,但您的 console.log 调用在此之前被触发(这就是异步代码的工作原理!)。只需使用回调中的值。如果需要,从那里调用另一个函数,并将数据传递给它。

【讨论】:

  • Just use the value from the callback,怎么样?
  • 我的意思是从successGetList 内部使用results.rows.length,或者从那里调用另一个函数并传递它。确切的答案将取决于您要对值做什么...
  • 知道了。没有注意到回调是异步的。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
相关资源
最近更新 更多