相同的嵌套查询

时间:2012-10-10 16:28:08

标签: javascript sql closures nested

  

可能重复:
  javascript: Using the current for-loop counter-value inside a function() { }?

如果我运行下面的代码,第二个控制台日志输出只重复第一个控制台日志输出的最后一行。

我理解这是因为所有嵌套的Query 2都排队等待其他所有内容完成后运行。此外,由于我们在函数中有一个函数,这会创建一个'闭包',这意味着嵌套查询2只有一组变量,并且它是所使用的最终状态,因此只有最后一个查询1的结果是反复使用查询2.至少我认为这是正在发生的事情。问题是,如何更改它以便整个过程顺序工作?

谢谢!

db.transaction(function(tx){

    //  Query 1                 
    tx.executeSql("SELECT * FROM Products GROUP BY ssrt55", [], function(tx, listResults){
        for (var i = 0; i < listResults.rows.length; i++) {
            var lineData = listResults.rows.item(i);
            var productDescriptionSQL = "select * from ProductDescriptions where bsrt56 = " + lineData['SSRT55'];
            console.log(productDescriptionSQL);

            //  Query 2
            tx.executeSql(productDescriptionSQL, [], function(tx, descriptionResults){
                console.log(productDescriptionSQL);                         
            }, onError);    

        }
    }, onError);

});
First console log output
select * from ProductDescriptions where bsrt56 = 1.00
select * from ProductDescriptions where bsrt56 = 2.00
select * from ProductDescriptions where bsrt56 = 2.50
select * from ProductDescriptions where bsrt56 = 3.00
select * from ProductDescriptions where bsrt56 = 4.00

Second console log output
select * from ProductDescriptions where bsrt56 = 4.00 
select * from ProductDescriptions where bsrt56 = 4.00 
select * from ProductDescriptions where bsrt56 = 4.00 
select * from ProductDescriptions where bsrt56 = 4.00 
select * from ProductDescriptions where bsrt56 = 4.00

2 个答案:

答案 0 :(得分:1)

是的,如果您使用console.log(productDescriptionSQL);替换查询2中的loopdloop(tx, listResults)以便创建新变量,则所有处理都可以在此函数中进行,并且在运行所有查询时不会被覆盖最后在一起。

db.transaction(function(tx){

    tx.executeSql("SELECT * FROM Products GROUP BY ssrt55", [], function(tx, listResults){
        for (var i = 0; i < listResults.rows.length; i++) {
            var lineData = listResults.rows.item(i);
            //var lineData = listResults.rows[i].item[0];
            var productDescriptionSQL = "select * from HierarchyDescriptions where psrt56 = '" + lineData['SSRT55']+"'";
            console.log(productDescriptionSQL);

            tx.executeSql(productDescriptionSQL, [], function(tx, listResults){
                loopdloop(tx, listResults)
            }, onError);    

        }
    }, onError);

});

function loopdloop(tx, descResults){
    console.log(descResults.rows.length);
    for (var i = 0; i < descResults.rows.length; i++) {
        var descriptionData = descResults.rows.item(i);
        console.log(descriptionData['HDES56']);
    }
}

谢谢@James

答案 1 :(得分:0)

尝试更改:

var lineData = listResults.rows.item(i);

要:

var lineData = listResults.rows[i].item[0];