循环更新多个文档

Update more than one document in a loop

背景:

我使用 PouchDB (indexedDB) for an offline NW.js App and I'm new to no-sql. I also use the PouchDB plugin Upsert,这基本上会在后台执行 db.get() 和 db.put()。

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

有没有一种方法可以在循环中使用一个函数更新 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);
    });
}

我认为 Nolan Lawson 很快就会给出比我更好的答案,但无论如何……在您的循环中,您可以将每个从 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);
    });

诺兰在他的post“We have a problem with promises”中很好地阐述了这一点。

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

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)})