我正在使用Meteor.require('npmPackage')
NPM软件包。但是在npm包的回调函数中写入mongo时似乎出现错误。
错误:
Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
码
npmPackage.getInfo(function(err, data) {
UserSession.insert({
key: 'info',
value: data
});
console.log(data);
});
我尝试将代码包装在Fiber中,但仍显示相同的错误消息:
Fiber(function() {
npmPackage.getInfo(function(err, data) {
UserSession.insert({
key: 'info',
value: data
});
console.log(data);
});
}).run();
问题:应该如何Meteor.bindEnvironment
使用它才能使它起作用?
尝试使用wrapAsync
例如
npmPackage.getInfoSync = Meteor._wrapAsync(npmPackage.getInfo.bind(npmPackage));
var data = npmPackage.getInfoSync();
UserSession.insert({
key: 'info',
value: data
});
您可以根据需要添加参数npmPackage.getInfoSync()
(如果需要的话)。
关键是回调必须位于错误产生的光纤中。最好的方法是使用Meteor.bindEnvironment
。Meteor._wrapAsync
为您做到这一点并使代码同步。哪一个更好:)
Meteor._wrapAsync是一个未公开的方法,它接受的方法的最后一个参数是一个回调,第一个参数为error
,第二个参数为result
。就像您的回调一样。
然后,将回调包装为a Meteor.bindEnvironment
,然后等待,然后同步返回值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句