我创建了一个函数,它将从我的数据库中返回字符串“path”。
function getAudio(mid, cb) {
//mid is an array containing the id to some multimedia files.
for(i=0; i < mid.length; i++) {
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM Multimedia WHERE Mid=' + mid[i] + ' AND Type=' + 2, [], function(tx, results) {
//type=2 is audio. (type=1 is picture file etc) There is only one audiofile in the array.
if(results.rows.length > 0) {
path = results.rows.item(0).Path;
cb(path);
}
}, errorCB);
}, errorCBQuery);
}//end for
}//end getAudio()
当我删除 for 循环时,查询成功,当 for 循环存在时, errorCBQuery 或 errorCB 被调用。
关于如何解决这个问题的任何想法?谢谢:)
最佳答案
这是经典的闭包问题。 transaction
是一个异步 调用,这意味着您的循环在您传入的函数被触发之前完成。该函数具有对 i
变量的持久引用,而不是调用 transaction
时的副本。所以这些函数中的每一个(你在每个循环中生成一个)都看到 i == mid.length
因此 mid[i]
是 undefined
并且你的 SQL 变得一团糟。
您需要做的是让回调关闭另一个在循环继续时不会改变的变量。通常的方法是使用工厂函数:
function getAudio(mid, cb) {
//mid is an array containing the id to some multimedia files.
for(i=0; i < mid.length; i++) {
db.transaction(makeTx(mid[i]), errorCBQuery);
}//end for
function makeTx(val) {
return function(tx) {
tx.executeSql('SELECT * FROM Multimedia WHERE Mid=' + val + ' AND Type=' + 2, [], function(tx, results) {
//type=2 is audio. (type=1 is picture file etc) There is only one audiofile in the array.
if(results.rows.length > 0) {
path = results.rows.item(0).Path;
cb(path);
}
}, errorCB);
};
}
}//end getAudio()
在那里,我将 mid[i]
传递给 makeTx
函数,该函数返回将传递给 的函数>交易
。我们返回的函数关闭了调用创建它的 makeTx
的 val
参数,这不会改变。
这是对代码的最小重写;你也许可以更进一步。例如,参见 missingno 对 re parameterized statements 问题的评论。
旁注:您似乎没有在任何地方声明 i
或 path
。如果这是真的,那么您将成为 The Horror of Implicit Globals 的猎物。 。建议声明它们。
关于SQLite 查询中的 javascript for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9871319/