简体   繁体   中英

Wrapping Collection.insert

I have this Method in Meteor.js "main.js - Server".

Meteor.methods({
  messageSent: function (message) {
    var apiai = require('apiai');

    var app = apiai("TOKEN");
    var request = app.textRequest(message, {
      sessionId: '<unique session id>'
    });

    request.on('response', function(response) {
      console.log(response);
      console.log(response.result.fulfillment.speech);
      Meteor.wrapAsync(gateway.transaction.sale);
      Messages.insert({
        message: response.result.fulfillment.speech,
        timestamp: new Date(),
        username: 'gotoAndBot'
      });
    });

    request.on('error', function(error) {
      console.log(error);
    });

    request.end();
  }  
});

That gets answer from api.ai and tries to add api.ai's answer into Collection.

But this returns error:

ERROR: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnviorment.

That is cause by the Messages.insert line.

As suggested in the comment already, the answer is to wrap your callback in Meteor.bindEnvironment so that it runs within a fiber with all the necessary variables attached. So your code would be:

Meteor.methods({
  messageSent: function (message) {
    var apiai = require('apiai');

    var app = apiai("TOKEN");
    var request = app.textRequest(message, {
      sessionId: '<unique session id>'
    });

    request.on('response', Meteor.bindEnvironment(function(response) {
      Messages.insert({
        message: response.result.fulfillment.speech,
        timestamp: new Date(),
        username: 'gotoAndBot'
      });
    }));

    request.on('error', function(error) {
      console.log(error);
    });

    request.end();
  }  
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM