问题
I'm using Meteor.require('npmPackage')
to use a NPM package. However I seem to be getting an error when writing to mongo in npm package's callback function.
Error:
Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
Code
npmPackage.getInfo(function(err, data) {
UserSession.insert({
key: 'info',
value: data
});
console.log(data);
});
I tried wrapping the code within Fiber but the same error message is still shown:
Fiber(function() {
npmPackage.getInfo(function(err, data) {
UserSession.insert({
key: 'info',
value: data
});
console.log(data);
});
}).run();
Question: How should Meteor.bindEnvironment
be used to get this to work?
回答1:
Try using wrapAsync
e.g
npmPackage.getInfoSync = Meteor._wrapAsync(npmPackage.getInfo.bind(npmPackage));
var data = npmPackage.getInfoSync();
UserSession.insert({
key: 'info',
value: data
});
You can add params into npmPackage.getInfoSync()
if you want (if it takes any).
The thing is the callback needs to be in a fiber which is where the error comes from. The best way to do it is with Meteor.bindEnvironment
. Meteor._wrapAsync
does this for you and makes the code synchronous. Which is even better :)
Meteor._wrapAsync is an undocumented method that takes in a method who's last param is a callback with the first param as error
and the second as a result
. Just like your callback.
It then wraps the callback into a Meteor.bindEnvironment
and waits for it then returns the value synchronously.
来源:https://stackoverflow.com/questions/20041177/meteor-code-must-always-run-within-a-fiber-error-when-using-npm-package