6

In my Meteor client code, I'm trying to use a third party API that only has asynchronous calls. How can I use Meteor.wrapAsync on the client to make calls to this API in a synchronous style? The docs seem to indicate that this is possible: http://docs.meteor.com/#/full/meteor_wrapasync

Here is some sample code I would like to call in a synchronous style:

var func1 = function(callback) {
  Meteor.setTimeout(function() {
    console.log('func1 executing');
    callback(null, {success: true});
  }, 2000);
};

var func2 = function(callback) {
  Meteor.setTimeout(function() {
    console.log('func2 executing');
    callback(null, {success: true});
  }, 1000);
};

var wrapped1 = Meteor.wrapAsync(func1);
var wrapped2 = Meteor.wrapAsync(func2);

Template.test.rendered = function() {
    wrapped1();
    console.log('After wrapped1()');
    wrapped2();
    console.log('After wrapped2()');
};

Currently, this produces this output:

After wrapped1()
After wrapped2()
func2 executing
func1 executing

I'd like it to produce:

func1 executing    
After wrapped1()
func2 executing
After wrapped2()

I've put this code into a MeteorPad here: http://meteorpad.com/pad/fLn9DXHf7XAACd9gq/Leaderboard

Dave Allen
  • 73
  • 6
  • This is not possible, the browser environment is asynchronous by design, see this answer for more info about why `Meteor.wrapAsync` is defined on the client but resolves to a callback behavior : http://stackoverflow.com/questions/26058205/meteor-wrapasync-syntax/26058613#26058613 – saimeunt Apr 06 '15 at 20:15

1 Answers1

2

Meteor.wrapAsync works on the client for the sake of isomorphic code. This is so you can make code that you can share on the client and server without Meteor crashing or complaining.

It is not possible to have synchronous code on the client. At least without using ES6 features which are not available on all browsers.

As in the comment by saeimeunt Meteor.wrapAsync will require a callback on the client.

Tarang
  • 75,157
  • 39
  • 215
  • 276
  • So it's available to call on the client, but it returns broken functions `Can't make a blocking HTTP call from the client; callback required.`, that's not really isomorphic to me! (I know, not your fault). IMHO, it could return a Promise-returning function, to be somewhat useful on the client, ala de-nodeify. – Dean Radcliffe Aug 19 '15 at 09:09