pouchdb似乎正在保存,但不保存

时间:2019-01-09 08:16:19

标签: cordova pouchdb

我正在研究cordova应用程序。由于本地存储空间不足,我开始使用pouchdb。我将保存在本地存储区域中的json数据发布到pouchdb。就像创建了文档一样。但是该文件不会发生。当我使用“获取所有文档”功能时,返回0行。

create: function (item) {
            myApp.db.post(item).then(function (response) {
                console.log("Response id " + response.id + " item " + item);
            }).catch(function (err) {
                console.log(err.name === 'conflict' ? "Conflict occurred - possible duplicate " : "Error " + err);
            });
  },
    loadData: function (callback) {
        myApp.db.allDocs({ include_docs: true, attachments: true }, function (err, response) {
            if (err) console.log(err);
            var rows = response.rows;
            for (var i = 0; i < rows.length; i++) {
                console.log(rows[i].doc);
                alert(JSON.stringify(rows[i].doc));
                //var taskItem = myApp.services.tasks.createTaskElem(rows[i].doc);
                //if (rows[i].doc.completed)
                //    myApp.services.tasks.addToCompletedList(taskItem);
                //else myApp.services.tasks.addToPendingList(taskItem);
            }
        });
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

1 个答案:

答案 0 :(得分:0)

我相信您会被Javascript的异步特性所欺骗。在处理post命令时,JavaScript继续执行下一个任务... allDocs ...,但找不到数据,因为它仍在写入PouchDB。

如果您已经注意到,每个PouchDB API文档示例都有3个选项卡,可让您选择Callback,Promise或Async / Await替代项。我相信一旦知道了这一点,您就会发现Async / Await是到目前为止与PouchDB结合使用的最佳方法。

所以,请尝试以下方法,并告诉我您如何使用:

/*  Function to instantiate a new random JSON record */
const item = () => {
  return {
    _id: `Thing_${parseInt(1000*Math.random(), 10)}`,
    stuff: ' silly random remark ',
  }
};

/* Function to 'put', then retrieve, records from PouchDB */
const dbTest = async () => { // "async" advises JavaScript to expect (otherwise illegal) 'await' statements
  console.log(`
    Start ...
    `);
  try {
    /* Remember the item ID */
    const rndItemId = item();

    /* Store the random item in PouchDB */
    const response = await myapp.db.put(rndItemId); // Do NOT return until 'put' is complete

    /* Log the response from PouchDB */
    console.log(`response for <${rndItemId._id}> ....\n${JSON.stringify(response, null, 2)}`);

    /* Get back all the random items we 'put' in the Pouch so far */
    const result = await myapp.db.allDocs({ // Do NOT return until 'allDocs' is complete
      include_docs: true,
      attachments: true,
      startkey: 'Thing_0',
      endkey: 'Thing_999',
    });

    /* Log the result from PouchDB */
    console.log(`result ....\n${JSON.stringify(result, null, 2)}`);

  } catch (err) {
    console.log(err);
  }
  console.log(`
    ... done!
    `);
};
/* Call the above function */
dbTest();
/* Call it again */
dbTest();

快速说明:请注意使用put而不是post!请阅读12 pro tips for better code with PouchDB