2012-12-20 57 views
2

我在处理数据库应用程序时遇到了一些麻烦。看来我的JavaScript函数在我的SQL事务完成之前继续前进。以下是我正在经历的一个非常简化的版本。在实际的函数中,我试图在移动到for循环中的下一个值之前在表上做一些工作。它似乎在for循环中执行所有操作,然后完成SQL事务。For SQL在SQL事务完成之前继续执行

下面是示例代码:

function fillTables(){ 
    db.transaction(function (tx){ 
     for(var i=0; i<3; i++){ 
      console.log('Filling row '+i); 
      tx.executeSql(
         'INSERT INTO Numbers (Value) VALUES (?)', 
         [i], 
         function(){ 
          console.log('Inserted Row');  
         }, 
         errorCB); 
      console.log('moving on...'); 
     } 
    }); 
} 

控制台日志我希望看到的是:

Filling Row 0 
Inserted Row 
moving on... 
Filling Row 1 
Inserted Row 
moving on... 
Filling Row 2 
Inserted Row 
moving on... 

但是,我得到:

Filling row 0 
moving on... 
Filling row 1 
moving on... 
Filling row 2 
moving on... 
Inserted Row 
Inserted Row 
Inserted Row 

任何关于如何实现预期结果的想法?

+0

如果以下答案中的任何一个给出了您的问题的解决方案,请点击答案旁边的复选标记以接受答案。这将有助于未来用户搜索相同问题的答案。谢谢。 – SnareChops

回答

1

tx.executeSql()是一个异步函数,行为适当。我会为你寻找同步方法并编辑我的回应。

所以根据我所阅读的功能是异步只是由于HTML5规范。此外,如果您以某种方式同步运行它,它将返回“无效状态”错误。

0

tx.executeSql()是一个异步函数,在这种情况下,您需要在函数完成后执行递归调用。

function fillTables() { 
    db.transaction(function (tx){ 
     var recursiveFunction = function (index, length) { 
      if (index < length) { 
       console.log('Filling row ' + index); 
       tx.executeSql(
        'INSERT INTO Numbers (Value) VALUES (?)', 
        [index], 
        function(){ 
         console.log('Inserted Row'); 
         console.log('moving on...'); 
         recursiveFunction(++index, length);  
        }, 
        errorCB); 
      } 
     } 

     recursiveFunction(0, 3); 
    }); 
} 
相关问题