1

This Meteor server code makes a DDP call to external service serv2 and once it gets the result, it suppose to send back to the client which made the call, but it is not.

What is the best fix? Should I take advantage of MongoDB reactiveness?

/////////////////////////// client/main.js \\\\\\\\\\\\\\\\\\\\\\\\\\

Template.hello.events({
  'click button'(event, instance) {
    Meteor.call('service2', function (err, res) {
      if (!err) {
        console.log('got it');  //=> prints right away without waiting.
        console.log(res);       //=> print undefined <==================
        instance.msg.set(res);
      }
    });
  }
});

/////////////////////////// server/app.js \\\\\\\\\\\\\\\\\\\\\\\\\\

import { Meteor } from 'meteor/meteor';
import { DDP } from 'meteor/ddp-client';

let serv2 = DDP.connect('localhost:7001');

Meteor.methods({
  'service2': function () {
    serv2.call('service2', function (err, res) {
      if (!err) {
        console.log(res); //=> prints OK
        return 'service 1 calling service 2 <br> + res'; //<====== failed to return.
      }
    });
  }
});
Fred J.
  • 5,759
  • 10
  • 57
  • 106

1 Answers1

2

This is what is happening:

  • Client calls the service2 method on the server and waits for a DDP response before calling the callback.

  • The server starts to run the service2 function in which your serv2.call() line initiates the .call() to your :7001 server.

  • serv2.call() immediately returns, since the call is asynchronous.

  • The service2 function is now complete, and returns undefined since it does not have any return statement.

  • Your client callback gets this result and runs as you described.

  • At some later point the call to serv2 is complete, and it's callback is run, but since no one is listening to its return value it is lost in the void...

To make your setup work you need to make service2() wait for the result of serv2.call(). The method Meteor.wrapAsync() exists for this purpose. See http://docs.meteor.com/api/core.html#Meteor-wrapAsync.

You might also benefit from the discussion here: Meteor: Proper use of Meteor.wrapAsync on server

Community
  • 1
  • 1
Jesper We
  • 5,977
  • 2
  • 26
  • 40