在主函数的回调中获取返回值
我正在开发一个使用 HTML5 和 Web 数据库存储的应用程序。
我想在表中插入一行并返回使用以下命令创建的新 ID(表的主键):
function insertIntoTable(title, text, sketchFileName, categoryId)
{
var db = window.openDatabase('xxx', '1.0', 'xxx database', 5*1024*1024);
var returnedId = -1;
db.transaction(
function (tx) {
if (sketchFileName == '')
{
tx.executeSql('INSERT INTO TableXXX (title, content, created, categoryID) VALUES (?, ?, ?, ?)',
[title, text, Date.now(), categoryId],
function (transaction, resultSet) {
if (resultSet.rowsAffected) {
returnedId = resultSet.insertId;
}
}, handleSQLError);
}
}, handleSQLError);
);
return returnedId;
}
但我总是得到 -1。我使用 Safari 开发模式在表中看到新行。
有什么建议吗?
I'm developing an application using HTML5 and web database storage.
I want to insert an row in a table and return the new ID (table's primary key) created using:
function insertIntoTable(title, text, sketchFileName, categoryId)
{
var db = window.openDatabase('xxx', '1.0', 'xxx database', 5*1024*1024);
var returnedId = -1;
db.transaction(
function (tx) {
if (sketchFileName == '')
{
tx.executeSql('INSERT INTO TableXXX (title, content, created, categoryID) VALUES (?, ?, ?, ?)',
[title, text, Date.now(), categoryId],
function (transaction, resultSet) {
if (resultSet.rowsAffected) {
returnedId = resultSet.insertId;
}
}, handleSQLError);
}
}, handleSQLError);
);
return returnedId;
}
But I always get -1. I see the new row in table using Safari development mode.
Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果将 returnedId 的声明移至函数外部,然后调用该函数两次,您将看到返回值是第一个插入的 id,因此正在设置它。看起来,因为数据库是异步的,所以 id 是在函数返回后设置的,这是有道理的。
根据 W3C 规范,应该有一个 openDatabaseSync 可以用来代替 openDatabase,但我无法让它在 Safari (5.0.1) 中工作。
显然,我不知道您的代码在您发布的代码片段之外是什么样子,但希望您能够重构它,这样您就不需要返回值,而是可以在回调中管理返回的 id 。
If you move the declaration of returnedId to outside of the function and then call the function twice you'll see the returned value is the id of the first insert so it is being set. It looks like, because the database is asynchronous, the id is being set after your function returns, which makes sense.
According to the W3C spec, there should be an openDatabaseSync which can be used instead of openDatabase but I couldn't get that to work in Safari (5.0.1).
Obviously, I don't know what your code looks like outside of the snippet you've posted but hopefully you'll be able to refactor it so you don't need to return the value and instead can manage the returned id in the callback.