'Meteor code must always run within a Fiber' error when using NPM package
Asked Answered
P

1

3

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?

Perjure answered 18/11, 2013 at 6:7 Comment(2)
It would be wise to place the version of the Meteor you are using. Meteor is in constant development, and a newer version could break code developed in older versions. Also, much of the API is also undocumented. What developers do is study the shipped packages.Mississippian
Will do that in the future. I'm currently using v0.6.6.3Perjure
C
5

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.

Climatology answered 18/11, 2013 at 8:39 Comment(1)
Thanks it works! How do I also retrieve err from npmPackage.getInfoSync() and do the error checking like in the original non-working code?Perjure

© 2022 - 2024 — McMap. All rights reserved.