PouchDB事务错误

3

我希望有人能够提供一些想法。这个问题给我带来了一些真正的困扰:

Uncaught (in promise) DOMException: Failed to execute 'transaction' on 'IDBDatabase': The database connection is closing. {message: "Failed to execute 'transaction' on 'IDBDatabase': The database connection is closing.", name: "InvalidStateError", code: 11, stack: "Error: Failed to execute 'transaction' on 'IDBData…ss (http://x.example.com/jav.js:352:56)", INDEX_SIZE_ERR: 1…}n.openTransactionSafely @ pouchdb-3.3.1.min.js:7e._get @ pouchdb-3.3.1.min.js:8(anonymous function) @ pouchdb-3.3.1.min.js:7(anonymous function) @ pouchdb-3.3.1.min.js:10(anonymous function) @ pouchdb-3.3.1.min.js:10(anonymous function) @ pouchdb-3.3.1.min.js:10(anonymous function) @ pouchdb-3.3.1.min.js:10(anonymous function) @ pouchdb-3.3.1.min.js:10$.ajax.success @ jav.js:352j @ jquery.js:3094k.fireWith @ jquery.js:3206x @ jquery.js:8259k.cors.a.crossDomain.send.b @ jquery.js:8600

这是我在PouchDB中偶尔遇到的错误。这个错误发生在以下情况下:
1. 获取所有任务。 2. 逐个将每个任务发送到 WebService 中以存储在远程数据库中。 3. 当响应返回时,删除 PouchDB 中的该任务。
操作的原理是只有当 WebService 确认后,才会从手机上(使用此应用的)删除任务。但问题是,由于这个错误,它从不删除第一个任务,这意味着用户会重复同步,想知道为什么它不起作用,所以出现了很多重复项。
该错误发生在第三个步骤周围,在get调用时。它似乎发生在第一次调用时(例如,如果有3个任务,则尝试获取第一个任务时会失败)。
我只想强调一点-这并不总是发生。只是偶尔发生。通过搜索我发现关于此问题的文档不多,但它似乎是由某种竞争条件引起的。
即使问题在于 PouchDB 本身,我希望自己能够重新编写代码,以便这不会成为一个大问题。
        var tasks = [];
        myDatabase.allDocs({include_docs: true}).then(function(result) {
            totalTasks = result.total_rows;

            // Save the tasks
            for (var i = 0; i < totalTasks; i++) {
                tasks.push(result.rows[i].doc.task)
            }

            // If there are tasks...
            if (tasks.length > 0) {
                var syncLogic = function() {

                    // When the user clicks the sync button; send it off
                    var postData = {
                        // Use the username previously submitted
                        auth: {
                            username: username,
                        },

                        // Empty task because this is a shell - we'll overwrite that when we actually send the task
                        task: ''
                    };

                    // Link to the webservice
                    var postLink = syncHttpLink;

                    // Recursive function, because we need to send tasks one at a time
                    // That way if there's a failure, we'll never have to send the whole lot again
                    // and risk duplicate tasks.
                    var sendToWebService = function (count) {
                        postData.task = tasks[count];
                        count++;

                        var jsonStringifyPostData = JSON.stringify(postData);

                        $.ajax({
                            url: postLink,
                            cache: false,
                            type: 'POST',
                            timeout: 180000,
                            data: jsonStringifyPostData,

                            // When the data has been sent
                            complete: function () {
                                // Complete - nothing here currently
                            },

                            // When it's successful we'll get a response
                            success: function (data) {
                                if (!data.authenticates) {
                                    // Log auth error
                                    // ...
                                }

                                if (data.authenticates && data.synced) {
                                    // They logged in, the task has synced. Delete the document from the internal database.

  // THIS LINE HERE IS WHERE IT CAUSES THE ERROR:
  myDatabase.get(data.id).then(function (doc) {
                                        myDatabase.remove(doc, function(error, response) {
                                            if (error) {
                                                // Log the error
                                                console.log("Database delete error:" + error);
                                            }

                                            else {
                                                console.log("Database record deleted: " + data.id);

                                                // Send the next task
                                                if (count <= (totalTasks - 1)) {
                                                    sendToWebService(count);
                                                }

                                                else {
                                                    // Finished
                                                    exitSync();
                                                }
                                            }
                                        });
                                    });
                                }
                            },

                            // If there's an error...
                            error: function (xhr, status, error) {
                                console.log(error);
                            }
                        });
                    };

                    // First call!
                    sendToWebService(0);
                };
            }
        });

非常感谢您的帮助。


我在 Github 上开了一个 issue:https://github.com/pouchdb/pouchdb/issues/3802。在那里讨论可能比在 Stack Overflow 上更实际。 - nlawson
另外还有一件事:如果你使用Promise.all()而不是手动创建任务队列,你可以大大简化你的代码。你可以通过PouchDB.utils.Promise来使用PouchDB中的Promises。 - nlawson
1个回答

3

嗯,我知道这个问题,但我以为只有在使用map/reduce查询和destroy()时才可能出现。如果你都没有使用(好像是这样),那么这就是一个非常有趣的数据点。您可以提供一个可重现的实时测试用例吗?

另外,您使用的是哪个浏览器和PouchDB的哪个版本?

编辑: 我使用Promise.all重写了您的代码,这样您就可以看到它如何节省大量编码!虽然不是直接与您的问题相关,但我喜欢向人们传授Promise的乐趣。 :)

myDatabase.allDocs({
  include_docs: true
}).then(function(result) {
  // post all the data
  return PouchDB.utils.Promise.all(result.rows.map(function (row) {
    var postData = JSON.stringify({
      auth: { username: username },
      task: row.doc.task
    });
    return new PouchDB.utils.Promise(function (resolve, reject) {
        $.ajax({
          url: postLink,
          cache: false,
          type: 'POST',
          timeout: 180000,
          data: postData,

          success: function(data) {
            if (!data.authenticates) {
              reject(new Error('authentication error'));
            } else {
              // resolve the promise with the doc, so it will appear in the next step
              resolve(row.doc);
            }
          },

          error: reject
      }));
    });
  });
}).then(function (docs) {
  // remove all the docs
  return PouchDB.utils.Promise.all(docs.map(function (doc) {
    return myDatabase.remove(doc);
  }));
}).catch(function (err) {
  // any errors along the way will end up in a single place
  console.log(err);
});

嗨,我也遇到了同样的问题。我可以分享我的代码,这样你就可以看看了。这很紧急,请帮忙。非常感谢任何帮助。 - Priyank

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接