How do this in async mode?


#1

Hello!
I need Meteor application that get data from external sources(on server side) and put it on client-side. This is temporary data and I don’t need to put it on server Mongo. On server DB I store auth data for this external sources. I do this in sync mode, but I think this is not optimal, especially if we have many sources. I try async code but I have problem. I can’t understand how associate call back function and data source? From which callback(source) I get this data? This is my server code:

Meteor.methods({
doRequest: function (partNumber) {
    check(partNumber, String);

    for (var i = 0; i < sources.length; i++) {
        sources[i].params.nr = partNumber;

        HTTP.call("POST", sources[i].url, { auth: sources[i].auth, params: sources[i].params }, requestHandler);
    }

    function requestHandler(err, res) {
        if (err) {
            throw new Meteor.Error("not-response", "Remote server not responding");
        }
       // price - client collection

        Meteor.publish("price", function() {
               // put in client Mongo collection
                this.added('price', Random.id(), [res.content]);
                this.ready();
            });
    }
}

#2

Try this.unblock http://docs.meteor.com/#/full/method_unblock.

How about doing this completely inside Meteor.publish. When client subscribed you can check it’s ready() reactively and wait.

Meteor.publish("price", function(partNumber) {
    check(partNumber, String);

    var res;

    for (var i = 0; i < sources.length; i++) {
        sources[i].params.nr = partNumber;

       try {
           res = HTTP.call("POST", sources[i].url, { auth: sources[i].auth, params: sources[i].params });
           this.added('price', Random.id(), [res.content]);
           //this.ready(); //maybe
       } catch (e) {
          // Got a network error, time-out or HTTP error in the 400 or 500 range.
      }
   }

   this.ready();
});

#3

Thank you. I try this.


#4

I think a method might be the better solution here. Use fibers/future via Meteor.npmRequire to handle asynchronicity.