在循环中更新多个文档

时间:2017-06-04 19:24:13

标签: javascript indexeddb pouchdb upsert

背景:

我使用PouchDB(indexedDB)作为离线NW.js应用程序,我是no-sql的新手。我还使用PouchDB插件Upsert,这基本上在后台执行db.get()和db.put()。

问题:
我动态创建 n 文档,在另一个函数中我想用循环中的 upsert 函数更新它们,但我必须返回我要更新的文档。因此循环在第一次运行时停止(逻辑上,只是正常行为)。

有没有办法在循环中用一个函数更新 n 文档?

这是我的代码示例:

var temp = $('#number_discuss_points').val();

for (i = 1; i < temp; i++) {
    var v1= $('#discusspoint_heading' + i).val();
    var v2= $('#discusspoint_subheading' + i).val();
    var v3= $('#point_number' + i).val();
    var v4= $('#dpoint_deadline' + i).val();
    var v5= $('#responsible_person' + i).val();
    var v6= $('#dp_text' + i).val();  

    db.upsert(id_body + i, function (sheet) {
        sheet._id = id_body + i;
        sheet.discusspoint_heading = v1;
        sheet.discusspoint_subheading = v2;
        sheet.point_number = v3;
        sheet.dpoint_deadline = v4;
        sheet.responsible_person = v5;
        sheet.dp_text = v6;

        return sheet; //Logically, the functions stops here and return everthing with 1

    }).then(function (result) {
        console.log(result);
    }).catch(function (err) {
        console.log(err);
    });
}

2 个答案:

答案 0 :(得分:0)

我认为Nolan Lawson很快就会得到比我更好的答案,但无论如何......在你的循环中你可以将每个返回的promise从db.upsert添加到一个数组中。在循环之后,您可以使用Promise.all来处理所有这样的承诺:

var temp = $('#number_discuss_points').val();

var promise_list = [];

for (i = 1; i < temp; i++) {
    var v1= $('#discusspoint_heading' + i).val();
    var v2= $('#discusspoint_subheading' + i).val();
    var v3= $('#point_number' + i).val();
    var v4= $('#dpoint_deadline' + i).val();
    var v5= $('#responsible_person' + i).val();
    var v6= $('#dp_text' + i).val();  

    promise_list.push(db.upsert(id_body + i, function (sheet) {
        sheet._id = id_body + i;
        sheet.discusspoint_heading = v1;
        sheet.discusspoint_subheading = v2;
        sheet.point_number = v3;
        sheet.dpoint_deadline = v4;
        sheet.responsible_person = v5;
        sheet.dp_text = v6;

        return sheet; //Logically, the functions stops here and return everthing with 1
    }));
}

Promise.all(promise_list).then(function (result_list) {
    for(var result in result_list) {
        console.log(result);
    }
    }).catch(function (err) {
        console.log(err);
    });

Nolan在他的帖子“We have a problem with promises”中非常清楚地表达了这一点。

答案 1 :(得分:0)

首先在for循环中创建一个docs数组:

docArray=[]

for(i=1;i<10;i++){
    /* Create doc */
    doc={}
    doc._id=i
    doc.whatever='The Power of '+ i
    /* Push doc to array */
    docArray.push(doc)
}

现在,将docArray缩减为链式承诺:

docArray.reduce((seq,doc)=>{
    return seq.then(()=>{
        /*Chain "db.pusert" promise to seq*/
        return db.upsert(doc._id,function(docOLD){return doc})
    });
},Promise.resolve()/* Initial value of seq */)
.then(res=>{console.log('All "db.upserts" resolved')})
.catch(err=>{throw new Error(err)})
相关问题