2017-04-04 50 views
0
function add(one, two, three) { 
    db.transaction(function (tx) { 
    tx.executeSql('INSERT INTO results (one, two, three) VALUES (?,?,?)', [one, two, three]); 
    }), function() { 
     console.log('add transaction ok'); 
    }); 
} 

$('#add').click(function() { 
    $("tr.row").each(function() { 
    var one = $(this).find("input.one").val(); 
    var two = $(this).find("input.two").val(); 
    var three = $(this).find("input.three").val(); 
    add(one, two, three); 
    }); 

    alert("Done"); 
}); 

嗨,我试图点击一个按钮,它会在表的每一行中找到输入值,并将这些值插入到数据库中。表行数量有时可能会有所不同,也许3其他时间可能是10.等待每个包含数据库更新然后重定向

我已经使用jquery .each函数来执行此调用异步函数。整个过程起作用。我现在想要做的是当.each()函数完成alert()时。在代码原样的情况下,我首先收到警报,然后控制台记录事务是否正常,但我希望最后得到警报。

而不是理想的警报,我想直接到另一个页面,但我不能如果交易不完成第一。

我看了下面的解决方案可用在这个链接https://salesforce.stackexchange.com/questions/12424/wait-for-each-contained-async-calls-to-complete-before-redirect。实施这个警报是马上进行,交易通话甚至没有开始。

回答

0

首先 - 我不确定你应该从客户端写入SQL。包含要添加的值的ajax请求应该发送到服务器,然后服务器应该更新数据库,以便没有人能够破解您的查询。所以你已经被警告过了。但这里是如何在客户端执行此操作的:

更新您的数据库是一个异步任务。您需要提供一个回调或返回一个承诺时通知您更新完成:

function add(one, two, three) { 
    return new Promise(function (resolve, reject) { 
    db.transaction(function (tx) { 
     tx.executeSql('INSERT INTO results (one, two, three) VALUES (?,?,?)', [one, two, three]); 
    }, function (res) { 
     resolve(res); 
    }); 
    }); 
} 

$('#add').click(function() { 
    $("tr.row").each(function() { 
    var one = $(this).find("input.one").val(); 
    var two = $(this).find("input.two").val(); 
    var three = $(this).find("input.three").val(); 
    add(one, two, three).then(function (result) { 
     alert(result); 
    }); 
    }); 
}); 

我不知道你的db.transation如何处理失败,但你需要有调用reject处理程序(如reject(err) )。

编辑:你可能想,如果你想等到所有的行更新,而不是反应他们,因为他们应对考虑使用Promise.all(这可能是也可能不是一个很好的适合你的使用情况)

$('#add').click(function() { 
    var promiseList = $('tr.row').map(function() { 
     var $this = $(this); 
     var one = $this.find('input.one').val(); 
     var two = $this.find('input.two').val(); 
     var three = $this.find('input.three').val(); 

     return add(one, two, three); 
    }); 

    Promise.all(promiseList).then(function (resultRows) { 
     resultRows.forEach(function (rowTransactionResult, index) { 
      // do something with each result 
     }); 
    }) 
}); 
+0

哎,我正在做的PhoneGap移动应用程序,数据库是设备,其中应用程序使用本地存储。 编辑:即时尝试使每个完成后的警报,你的解决方案是在每个? – JMa

+0

如果数据库对设备是本地的,那么通过这种方式这将起作用。我不知道你的应用程序是什么或做什么,所以我不能确定地说这种方法是否是一个好主意。 – Brian

0

您可以使用承诺来管理异步任务。

function add(one, two, three) { 
 
    return new Promise(function(resolve, reject) { 
 
    try { 
 
     setTimeout(function() { resolve([one, two, three]) }, 2000); 
 
    } catch (e) { 
 
     reject('oops!'); 
 
    } 
 
    }); 
 
} 
 

 
$('.button').on('click', function() { 
 
    add(1, 2, 3).then(function(res) { 
 
    alert(res); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button class="button">Click me!</button>