问题
This has been bothering me for a while so I thought I'd just do a quick QA on it:
If one has a normal nodeJS module or something and it has a async function on the server side. How do I make it synchronous. E.g how would I convert the nodejs fs.stat
asynchronous function to a synchronous one.
e.g I have
server side js
Meteor.methods({
getStat:function() {
fs.stat('/tmp/hello', function (err, result) {
if (err) throw err;
console.log(result)
});
}
});
If I call it from the client I get back undefined
as my result because the result is in a callback.
回答1:
There is a function (undocumented) called Meteor.wrapAsync
.
Simply wrap the function up
Meteor.methods({
getStat:function() {
var getStat = Meteor._wrapAsync(fs.stat);
return getStat('/tmp/hello');
}
});
Now you will get the result of this in the result
of your Meteor.call
. You can convert any async function that has a callback where the first parameter is an error and the second the result.
来源:https://stackoverflow.com/questions/19616776/writing-converting-meteor-synchronous-functions