在服务器上调用Collection.insert时,“Meteor代码必须始终在Fiber中运行”

时间:2012-04-17 14:13:18

标签: javascript meteor node-fibers

我在server / statusboard.js中有以下代码;

var require = __meteor_bootstrap__.require,
    request = require("request")   


function getServices(services) {
  services = [];
  request('http://some-server/vshell/index.php?type=services&mode=json', function (error, response, body) {
    var resJSON = JSON.parse(body);
     _.each(resJSON, function(data) {
       var host = data["host_name"];
       var service = data["service_description"];
       var hardState = data["last_hard_state"];
       var currState = data["current_state"];
       services+={host: host, service: service, hardState: hardState, currState: currState};
       Services.insert({host: host, service: service, hardState: hardState, currState: currState});
    });
  });
}

Meteor.startup(function () {
  var services = [];
  getServices(services);
  console.log(services);
});

基本上,它从JSON提要中提取一些数据并尝试将其推送到集合中。

当我启动Meteor时,我得到以下异常;

app/packages/livedata/livedata_server.js:781
      throw exception;
            ^
Error: Meteor code must always run within a Fiber
    at [object Object].withValue (app/packages/meteor/dynamics_nodejs.js:22:15)
    at [object Object].apply (app/packages/livedata/livedata_server.js:767:45)
    at [object Object].insert (app/packages/mongo-livedata/collection.js:199:21)
    at app/server/statusboard.js:15:16
    at Array.forEach (native)
    at Function.<anonymous> (app/packages/underscore/underscore.js:76:11)
    at Request._callback (app/server/statusboard.js:9:7)
    at Request.callback (/usr/local/meteor/lib/node_modules/request/main.js:108:22)
    at Request.<anonymous> (/usr/local/meteor/lib/node_modules/request/main.js:468:18)
    at Request.emit (events.js:67:17)
Exited with code: 1

我不太清楚这个错误意味着什么。有没有人有任何想法,或者可以提出不同的方法?

3 个答案:

答案 0 :(得分:48)

将功能包装在光纤中可能还不够,可能会导致意外行为。

原因是,与光纤一起,Meteor需要一组连接到光纤的变量。 Meteor使用附加到光纤的数据作为动态范围,使用第三方API的最简单方法是使用Meteor.bindEnvironment

T.post('someurl', Meteor.bindEnvironment(function (err, res) {
  // do stuff
  // can access Meteor.userId
  // still have MongoDB write fence
}, function () { console.log('Failed to bind environment'); }));

如果您想了解更多信息,请立即观看这些视频: https://www.eventedmind.com/posts/meteor-dynamic-scoping-with-environment-variables https://www.eventedmind.com/posts/meteor-what-is-meteor-bindenvironment

答案 1 :(得分:15)

如上所述,这是因为您在回调中执行代码。

您在服务器端运行的任何代码都需要包含在Fiber中。

尝试将getServices函数更改为:

function getServices(services) {
  Fiber(function() { 
    services = [];
    request('http://some-server/vshell/index.php?type=services&mode=json', function (error, response, body) {
      var resJSON = JSON.parse(body);
       _.each(resJSON, function(data) {
         var host = data["host_name"];
         var service = data["service_description"];
         var hardState = data["last_hard_state"];
         var currState = data["current_state"];
         services+={host: host, service: service, hardState: hardState, currState: currState};
         Services.insert({host: host, service: service, hardState: hardState, currState: currState});
      });
    });
  }).run();  
}

我遇到了类似的问题,这对我有用。我要说的是,我对此非常陌生,我不知道这是不是应该如何做。

你可能只能在光纤中包装你的insert语句,但我不是正面的。

答案 2 :(得分:7)

根据我的测试,你必须在我测试的代码中包装插入,类似于上面的例子。

例如,我这样做了,它仍然因Fibers错误而失败。

function insertPost(args) {
  if(args) {
Fiber(function() { 
    post_text = args.text.slice(0,140);
    T.post('statuses/update', { status: post_text }, 
        function(err, reply) {          
            if(reply){
                // TODO remove console output
                console.log('reply: ' + JSON.stringify(reply,0,4));
                console.log('incoming twitter string: ' + reply.id_str);
                // TODO insert record
                var ts = Date.now();
                id = Posts.insert({
                    post: post_text, 
                    twitter_id_str: reply.id_str,
                    created: ts
                });
            }else {
                console.log('error: ' + JSON.stringify(err,0,4));
                // TODO maybe store locally even though it failed on twitter
                // and run service in background to push them later?
            }
        }
    );
}).run();
  }
}

我做到了这一点并且运行良好且没有错误。

function insertPost(args) {
  if(args) { 
post_text = args.text.slice(0,140);
T.post('statuses/update', { status: post_text }, 
    function(err, reply) {          
        if(reply){
            // TODO remove console output
            console.log('reply: ' + JSON.stringify(reply,0,4));
            console.log('incoming twitter string: ' + reply.id_str);
            // TODO insert record
            var ts = Date.now();
            Fiber(function() {
                id = Posts.insert({
                    post: post_text, 
                    twitter_id_str: reply.id_str,
                    created: ts
                });
            }).run();
        }else {
            console.log('error: ' + JSON.stringify(err,0,4));
            // TODO maybe store locally even though it failed on twitter
            // and run service in background to push them later?
        }
    }
);
  }
}

我认为这可能有助于其他人遇到此问题。我还没有测试过内部代码并将其包装在光纤中后调用异步类型的外部服务。这也许值得测试。在我的情况下,我需要知道在我执行本地操作之前发生的远程操作。

希望这有助于解决这个问题。