首页 文章

Meteor插入方法回调应该执行异步

提问于
浏览
0

Hello Stackoverflow社区,

In nuts

我想知道为什么插入回调没有被正确调用async,因为文档说,有一个代码,如:

Meteor.methods({
  addUpdate: function (text) {
    Updates.insert({
      text: text,
      createdAt: new Date(),
      owner_email: Meteor.user().emails[0].address,
      owner_username: Meteor.user().username
    }, function(e, id) {
      debugger; //<-- executed first with 'e' always undefined
    });
    debugger; //<-- executed after
  }
});

回调函数内的 debugger 之后在 debugger 之前执行,如果函数是异步的,回调内的调试器应该在右边调用?

More info

我对流星很新,事情是我正在尝试制作一个小应用程序,并进行实验,现在我想确认我对这个案例中的一些概念的理解是“插入”方法 . 给出以下代码:

lib/collections/updateCollection.js

Update = function (params, id) {
  params = params || {};
  // define properties for update model such as text
  this._text = params.text;
}

Update.prototype = {
  // define some getters and setters, such as doc
  get doc() {
    return {
      createdAt: this.createdAt,
      text: this.text,
      owner_email: this.owner_email,
      owner_username: this.owner_username
    };
  },
  notify: function notify(error, id) {
    var client, notification, status;

    client = Meteor.isClient ? window.Website : false;
    notification = (client && window.Hub.update.addUpdate) || {}
    status = (!error && notification.success) || notification.error;

    if (client) {
      return client.notify(status);
    }
  }
  save: function save(callback) {
    var that;

    that = this;
    callback = callback || this.notify;

    Updates.insert(that.doc, function (error, _id) {
      that._id = _id;
      callback(error, _id); <-- here is the deal
    });
  }
}

lib/methods/updateService.js

updateService = {
  add: function add(text) {
    var update;

    update = new Update({
      text: text,
      createdAt: new Date(),
      owner_email: Meteor.user().emails[0].address,
      owner_username: Meteor.user().username
    });

    update.save();
  },

  // methods to interact with the Update object
};

lib/methods/main/methods.js

Meteor.methods({
  addUpdate: function (text) {
    updateService.add(text);
  }
});

我的期望是当客户端执行类似 Meteor.call('addUpdate', text); 之类的操作时,一切都很酷,显示成功的消息,否则错误是"truth"并显示错误消息 . 实际上发生的是回调总是被调用,错误未定义(如果一切都很酷),回调也没有被称为异步,它只是直接调用 .

即使我关闭连接,更新插入也会显示成功消息 .

任何的想法?也许我的应用程序结构让流星工作错了?我真的不知道 . 提前致谢 .

1 回答

  • 1

    您的代码在方法内执行 . 在客户端上,执行方法只是为了模拟服务器响应之前服务器将执行的操作(以便应用程序看起来响应更快) . 因为这里的DB更改只是模拟服务器已经在做什么,所以它们不会被发送到服务器,因此是同步的 . 在服务器上,所有代码都在Fiber内运行,因此它是同步的 . (但是,光纤并行运行,就像普通的回调 - 汤节点一样 . )

相关问题