使用 NPM 包时出现“Meteor 代码必须始终在 Fiber 内运行"错误 [英] 'Meteor code must always run within a Fiber' error when using NPM package
问题描述
我正在使用 Meteor.require('npmPackage')
来使用 NPM 包.但是,在 npm 包的回调函数中写入 mongo 时,我似乎遇到了错误.
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.
错误:
错误:Meteor 代码必须始终在 Fiber 中运行.尝试使用 Meteor.bindEnvironment 包装您传递给非 Meteor 库的回调.
代码
npmPackage.getInfo(function(err, data) {
UserSession.insert({
key: 'info',
value: data
});
console.log(data);
});
我尝试将代码包装在 Fiber 中,但仍显示相同的错误消息:
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();
问题:应该如何使用 Meteor.bindEnvironment
使其工作?
Question: How should Meteor.bindEnvironment
be used to get this to work?
推荐答案
尝试使用 wrapAsync
例如
npmPackage.getInfoSync = Meteor._wrapAsync(npmPackage.getInfo.bind(npmPackage));
var data = npmPackage.getInfoSync();
UserSession.insert({
key: 'info',
value: data
});
如果需要(如果需要),您可以将参数添加到 npmPackage.getInfoSync()
中.
You can add params into npmPackage.getInfoSync()
if you want (if it takes any).
问题是回调需要在纤维中,这是错误的来源.最好的方法是使用 Meteor.bindEnvironment
.Meteor._wrapAsync
为你做这件事并使代码同步.哪个更好:)
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 是一个未公开的方法,它接受一个方法,该方法的最后一个参数是一个回调,第一个参数为 error
,第二个参数为 result
.就像你的回调一样.
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.
然后将回调包装到 Meteor.bindEnvironment
并等待它然后同步返回值.
It then wraps the callback into a Meteor.bindEnvironment
and waits for it then returns the value synchronously.
这篇关于使用 NPM 包时出现“Meteor 代码必须始终在 Fiber 内运行"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!