Cri*_*sLC 1 javascript pouchdb
我有一个可以在PouchDB中创建或更新文档的功能,如下所示。第一次运行时,该功能可以完美运行。但是,即使._rev属性似乎正确,每个后续运行都会产生409错误。
function saveEventMatchesToDatabase(event, db) {
/* event: An event object from The Blue Alliance API. */
/* db: a reference ot the PouchDB database. */
/* Purpose: Given an event, extract the list of matches and teams, and save them to the database. */
TBA.event.matches(event.key, function(matches_list) {
var i = 0;
for (i = 0; i < matches_list.length; i++) {
var match = new Object();
var docrec = new Object();
match._id = 'matches/' + matches_list[i].key;
match.redTeam = matches_list[i].alliances.red.teams;
match.blueTeam = matches_list[i].alliances.blue.teams;
/* If the doc already exists, we need to add the _rev to update the existing doc. */
db.get(match._id).then(function(doc) {
match._rev = doc._rev;
docrec = doc;
}).catch(function(err) {
if ( err.status != 404 ) {
/* Ignore 404 errors: we expect them, if the doc is new. */
console.log(err);
}
});
db.put(match).then(function() {
// Success!
}).catch(function(err) {
console.log('\ndoc._rev: ' + docrec._rev);
console.log('match._rev: ' + match._rev);
console.log(err);
});
}
});
}
Run Code Online (Sandbox Code Playgroud)
下面是第二次运行此功能的示例控制台输出。match_list中的每个项目都会发生相同的错误,而不仅是间歇性的。
doc._rev: 1-7cfa2c6245dd939d8489159d8ca674d9
match._rev: 1-7cfa2c6245dd939d8489159d8ca674d9
r {status: 409, name: "conflict", message: "Document update conflict", error: true}
Run Code Online (Sandbox Code Playgroud)
我不确定我缺少什么,这就是导致此问题的原因。任何关于下一步寻找的建议将不胜感激。
第一个问题似乎是您在循环中使用了一个函数,这意味着内部函数内部使用的任何变量都会根据调用该函数的时间在您的脚下随机变化。您可以使用代替for循环forEach()。
但是,第二个问题是您没有正确使用Promise。您需要先等待的结果,get()然后再进行操作put()。因此,可能forEach()甚至根本不是您想要的。您可能想使用Promise.all(),然后兑现您的承诺。
我不久前写了一篇文章;许多人告诉我,即使时间长,也值得一读:“我们在诺言方面有问题。” 阅读该书,希望您在书末了解诺言。:)
| 归档时间: |
|
| 查看次数: |
4414 次 |
| 最近记录: |