开发者

Get a returned value in a callback on main function

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜