5

How do I use the Meteor wrapAsync?

Below is what I am trying to do

if (tempTreatment.groupId === undefined) {
      // create new group
      Meteor.wrapAsync(Meteor.call('createTreatmentGroup', salon, tempTreatment.groupName, tempTreatment.groupName));

      // get group id
      var getGroup = Meteor.wrapAsync(Meteor.call('getTreatmentGroup', salon, tempTreatment.groupName));

      console.log(getGroup);
      tempTreatment.groupId = getGroup._id;
}

I want to run these two Meteor.callfunctions synchronosly but I get undefined on console.log(getGroup); which shuold just return an object.

giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
Gravity123
  • 1,130
  • 3
  • 21
  • 39

1 Answers1

7

Meteor.wrapAsync is a server-side API designed to wrap Node.js asynchronous functions requiring a callback as last argument, to make them appear synchronous through the use of Futures, a Fibers sub-library. (more on this here : https://www.discovermeteor.com/blog/wrapping-npm-packages/)

It is not intended to be used client-side to turn asynchronous Meteor.call into a synchronous call because on the browser, Remote Method Invokation calls are ALWAYS asynchronous.

Long story short, you simply cannot achieve what you're trying to do, you have to use callbacks and nest your second method call inside the success callback of your first method call.

saimeunt
  • 22,666
  • 2
  • 56
  • 61
  • 1
    In 0.9.3 there is [Meteor.wrapAsync](http://docs.meteor.com/#meteor_wrapasync) which could be used `Anywhere`. Is this mistake ? – Kuba Wyrobek Sep 26 '14 at 11:37
  • 3
    I hadn't noticed that. I think they made a client version of `Meteor.wrapAsync` so that code using it could be put in the shared folder without triggering errors, but really this is intended for server use. In case no callback is provided, the client side version of `wrapAsync` simply defines a standard `logErr` callback to be used instead, which simply logs the error if present : https://github.com/meteor/meteor/blob/9608e6205019b69a302cde62e21fcae1c7d22e3d/packages/meteor/helpers.js#L108 – saimeunt Sep 26 '14 at 12:12