我想添加几个附件,我可以成功添加一个,但在循环时,它只会保存一张图像:5.png并出现冲突错误:
function addNewDoc() {
db.get('my0112doc', function(err, doc) {
if (err) {
return console.log(err);
}
// var blob = base64toBlob(imgSoucrce30m, 'image/png', 1024);
var blob =imgSoucrce30m;
var attachment = {
content_type: 'image/png',
data: blob
}
for (var i = 5; i >= 0; i--) {
var nameImg=i+'.png';
db.putAttachment('my0112doc', nameImg, doc._rev, blob, 'text/plain', function(err, res) {
if (err) {
return console.log(err);
}
});
}
});
}
====================新解决方案========================== ===============
在我的函数中,我已指定其修订版本_rev,但冲突仍然发生。我不明白为什么。
CustomPouchError {状态:409,名称:“冲突”,消息:“文档更新冲突”,错误:true}
function addNewDoc() {
db.get('my0112doc', function(err, doc) {
if (err) {
return console.log(err);
}
// var blob = base64toBlob(imgSoucrce30m, 'image/png', 1024);
var blob = imgSoucrce30m;
addAttachment(5,doc._rev,blob);
});
}
function addAttachment(counter,revId,blob) {
var nameImg = counter + '.png';
db.putAttachment('my0112doc', nameImg, revId, blob, 'text/plain', function(err, res) {
if (err) {
return console.log(err);
}
if (counter >= 0) {
addAttachment(counter - 1,revId,blob);
}
});
}
最佳答案
所以问题是 putAttachment
是异步的。所以你需要等待它解决之后才能再次放置。我不确定它是否返回一个 promise ,但如果没有,你可以这样做:
function addAttachment(counter) {
var nameImg= counter + '.png';
db.putAttachment('my0112doc', nameImg, doc._rev, blob, 'text/plain', function(err, res) {
if (err) {
return console.log(err);
}
if (counter >= 0) {
addAttachment(counter - 1);
}
});
}
addAttachment(5);
您还可以使用 Promise 执行某些操作,但这只是在上一次 put 完成时调用下一次迭代。一旦计数器为负数,它就会停止,就像您的 for 循环
一样。
关于javascript - Pouchdb 如何将附件放入 for 循环中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37152562/