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

时间:2015-03-25 17:25:24

标签: mongodb asynchronous meteor

我有这个循环:

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

基本上,它更新了一个文档工作台,最后删除了所有未更新的文档。

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

有没有更好的方法(不必使用此超时)?

谢谢,

1 个答案:

答案 0 :(得分:1)

几个想法:

  • upserts很快,不需要回调
  • 光纤用于服务器
  • 我不明白你的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});
  }
});