2015-08-20 46 views
0

你好#1社区,流星插入方法回调应该执行异步

在坚果

我很奇怪,为什么插入回调不被称为异步正确的文件说,有像代码:

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之后才执行,如果函数是异步回调SH内调试器应该被称为最后的权利?

更多信息

我很新与流星的事情是,我试图做一个小的应用程序,并尝试,现在我想证实我的理解有关此的一些概念case“插入”方法。给出以下代码:

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);,一切都很酷,显示了一个成功的消息,否则错误是“真理”,并显示错误信息。实际发生的事情是,回调总是被调用,并且未定义错误(如果一切都很酷),回调也不会被称为异步,它只是直接调用。

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

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

+0

where.doc'属性被填充到哪里? – Curtis

+0

在Update.property中,我只是跳过它来使代码更小,是一个getter。然后我要更新代码。 –

回答

1

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

+0

感谢您的回答@Gaelan,好吧,我想我得到了您,但是如果我想保留该功能,并且如果记录无法插入,使服务器响应错误怎么办?为了做这样的事情:用户进行更新并显示,但如果服务器无法插入,请将其删除。 –

+0

@AlexisDuran如果您使用'Meteor.apply'调用方法,则可以将回调作为最后一个参数传递。此回调将在服务器返回后调用。但是,客户端模拟仍将运行。如果出于某种原因,根本不需要客户端模拟,只是不要在客户端运行Meteor.methods调用(将其放在'server /'或'if(Meteor.isServer )'块)。 – Gaelan

+0

Got it!感谢您的帮助和时间。 –