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

≡放荡痞女 提交于 2019-12-22 10:15:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!