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

时间:2015-08-20 15:31:35

标签: javascript meteor frontend

Hello Stackoverflow社区,

坚果

我想知道为什么插入回调没有被正确调用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
  }
});

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

更多信息

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

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);的事情而且一切都很酷时,会显示成功的消息,否则错误就是&#34;真相&#34;并显示一条错误消息。实际发生的是,回调总是被调用,错误未定义(如果一切都很酷),回调也没有被称为异步,它只是直接调用。

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

有什么想法吗?也许我的应用程序结构让流星工作错了?我真的不知道。提前谢谢。

1 个答案:

答案 0 :(得分:1)

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