如何从 meteor 方法调用中获取返回值?



我使用此处描述的模式在客户端定义了一个 meteor 方法 https://guide.meteor.com/methods.html#advanced-boilerplate


// files.collection.js
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';
export const mediaFiles = new Mongo.Collection('media_files')
export const method_InsertFile = {
name: 'media_file.insert',
// Factor out validation so that it can be run independently (1)
validate(args) {
console.log('call validation: ', args)
new SimpleSchema({
title: { type: String },
filename: { type: String },
}).validate(args)
},
// Factor out Method body so that it can be called independently (3)
run({ filename, title }) {
let inserted_object = { title, filename }
mediaFiles.insert(inserted_object)
return inserted_object // object of interest
},
call(args, callback) {
console.log('call call method: ', args)
const options = {
returnStubValue: true,     // (5)
throwStubExceptions: true  // (6)
}
Meteor.apply(this.name, [args], options, callback);
}
};
if (Meteor.isServer) {
Meteor.methods({
// Actually register defined method with Meteor's DDP system
[method_InsertFile.name]: function (args) {
method_InsertFile.validate.call(this, args);
method_InsertFile.run.call(this, args);
},
});   
}

该方法的调用如下所示


import { method_InsertFile } from '../api/files.collection';
method_InsertFile.call(data, (err, res) => {
if (err) console.log("Return err ", err)
else {
console.log('result: ', res)
}
})

我想在方法调用结束时检索对象inserted_object。我尝试从方法定义的call块中返回一个承诺,如下所示

return new Promise((resolve, reject) => {
Meteor.apply(this.name, [args], options, (err, res) => {
resolve(res)
});
})

result返回undefined.

任何关于这是否可能以及如何完成它的指示都值得赞赏。

它是在Meteor.methods中声明的函数,它必须返回一些东西,以便将这个东西作为结果传递给你的方法调用回调。

在您的情况下,您只需返回run调用的结果。

在方法调用中,正确使用Meteor.apply执行Meteor.methods中声明的同名函数,并使用返回的值作为回调的结果。

最新更新