[英]Meteor, how to pass callback and error to caller method
In my Meteor.methods I have在我的 Meteor.methods 中,我有
var post= Posts.insert({...}, function(err,docsInserted){
Posts.update({...} , {...});
});
I want to create an insert model as suggested by David Weldon here .我想按照 David Weldon here 的建议创建一个插入模型。 My model looks like this:我的模型看起来像这样:
_.extend(Posts, {
ins:function (docID){
return Posts.insert({...});
}
});
In my methods I have this:在我的方法中,我有这个:
var post= Posts.ins(docID, function(err,docsInserted){
Posts.update({...} , {...});
});
How can I use a callback and error handling in the method?如何在方法中使用回调和错误处理? I'd like to be able to execute code when the Post is inserted successfully.我希望能够在成功插入 Post 时执行代码。
Looking at the documentation for collection.insert :查看collection.insert的文档:
Insert a document in the collection.在集合中插入一个文档。 Returns its unique _id.返回其唯一的 _id。
Arguments参数
doc Object文档对象
The document to insert.要插入的文档。 May not yet have an _id attribute, in which case Meteor will generate one for you.可能还没有 _id 属性,在这种情况下 Meteor 会为你生成一个。
callback Function回调函数
Optional.可选的。 If present, called with an error object as the first argument and, if no error, the _id as the second.如果存在,调用时将错误对象作为第一个参数,如果没有错误,则将 _id 作为第二个参数。
As I understand it, you want to execute a callback function if ins
executes successfully.据我了解,如果ins
执行成功,您希望执行回调函数。 Given that information, here's how I'd structure the code:鉴于这些信息,我将如何构建代码:
_.extend(Posts, {
ins:function (docID, callback){
Posts.insert({...}, function( error, id ) {
if( error ) {
callback( error, null );
} else {
callback( null, id );
}
});
}
});
You don't actually need to return anything.你实际上不需要返回任何东西。 You can just execute the callback function and pass parameters along appropriately.您可以只执行回调函数并适当地传递参数。 Then you can call the function with the following code:然后您可以使用以下代码调用该函数:
Posts.ins(docID, function(err,docsInserted){
if( error ) {
// Handle error.
} else {
Posts.update({...} , {...});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.