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?

Nyxynyx
  • 61,411
  • 155
  • 482
  • 830
  • 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. – Joseph Nov 18 '13 at 06:32
  • Will do that in the future. I'm currently using v0.6.6.3 – Nyxynyx Nov 18 '13 at 15:16

1 Answers1

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.

Tarang
  • 75,157
  • 39
  • 215
  • 276
  • Thanks it works! How do I also retrieve `err` from `npmPackage.getInfoSync()` and do the error checking like in the original non-working code? – Nyxynyx Nov 18 '13 at 15:15