我想在 Meteor 方法中调用一个异步函数,然后将该函数的结果返回给 Meteor.call。
(怎么)这可能?
Meteor.methods({
my_function: function(arg1, arg2) {
//Call other asynchronous function and return result or throw error
}
});
最佳答案
使用 Future 来做到这一点。像这样:
Meteor.methods({
my_function: function(arg1, arg2) {
// Set up a future
var fut = new Future();
// This should work for any async method
setTimeout(function() {
// Return the results
fut.ret(message + " (delayed for 3 seconds)");
}, 3 * 1000);
// Wait for async to finish before returning
// the result
return fut.wait();
}
});
更新:
要从 Meteor 0.5.1 开始使用 Future,您必须在 Meteor.startup 方法中运行以下代码:
Meteor.startup(function () {
var require = __meteor_bootstrap__.require
Future = require('fibers/future');
// use Future here
});
更新 2:
要从 Meteor 0.6 开始使用 Future,您必须在 Meteor.startup 方法中运行以下代码:
Meteor.startup(function () {
Future = Npm.require('fibers/future');
// use Future here
});
然后使用return
方法代替ret
方法:
Meteor.methods({
my_function: function(arg1, arg2) {
// Set up a future
var fut = new Future();
// This should work for any async method
setTimeout(function() {
// Return the results
fut['return'](message + " (delayed for 3 seconds)");
}, 3 * 1000);
// Wait for async to finish before returning
// the result
return fut.wait();
}
});
参见 this gist .
关于javascript - Meteor:在 Meteor.method 中调用异步函数并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12569712/