流星如何在循环中管理异步更新

meteor how to manage async updates in a loop

我有这个循环:

properties.forEach(function(property) {
    console.log("property: " + property);
    var upsertValues = {};
    upsertValues["ID"] = property.ID;
    Properties.upsert(upsertValues,
        {$set: property}, 
        function(err, nbr) {
            if(err)
                console.log(err);
            else
                console.log("upsert successful" + nbr);
        });
    });
    setTimeout(function () {
        Fiber(function() {
            Meteor.call("removeOldProperties", modification_date);
        }).run();
    }, 30000)
})

基本上,它会更新一堆文档,最后会删除所有未更新的文档。

我不得不使用超时,因为没有它,我会在更新之前删除文档,因为所有 Meteor.upsert 语句都是异步的。

是否有更好的方法(无需使用此超时)?

谢谢,

几个想法:

  • 更新速度快,无需回调
  • 光纤用于服务器
  • 我不明白你的 upsertValues 为什么是一个有效的查询。这是指文档 _id 吗?如果是这样,惯例是继续使用名称 _id,如果不是,我将使用更具描述性的名称。此代码是否有效??

剩下的:

var upsertsCompleted = 0;
properties.forEach(function(property) {
  Meteor.call("upsertProperties", property, function() {
    if (++upsertsCompleted === properties.length) {
    Meteor.call("removeOldProperties", modification_date);
  }
}

Meteor.methods({
  upsertProperties: function (property) {
    return Properties.upsert(property.ID, {$set: property});
  }
});