简体   繁体   中英

Constantly call / return a Meteor.method

I have a list of 600 url's that i want to loop over requests to.

Would it be possible to console.log the content of each one as i receive it as opposed to waiting for the 600 to finish then return it all as 1?

Sorry if this seems a bit vague, not sure on the correct terms to use to describe this.

  Meteor.methods({
    getNations: function () {
      this.unblock();

      var result = Meteor.http.get('https://www.easports.com/uk/fifa/ultimate-team/api/fut/item?jsonParamObject=%7B%22page%22:1%7D');

      var totalPages = JSON.parse(result.content).totalPages;

      for (var i = 1; i < totalPages; i++) {
        try {
          var page = Meteor.http.get('https://www.easports.com/uk/fifa/ultimate-team/api/fut/item?jsonParamObject=%7B%22page%22:' + i + '%7D');

          console.log(JSON.parse(page.content));
        } catch(e) {
          console.log('Cannot get page', e);
        }
      }

      return result;
    }
  })

This will get all the pages, insert them into a collection and make them available on the client. There are a few caveats though. If you call the method multiple times you will get duplicates in the database, not sure if that's what you intended. Also, the error logging only happens on the server and is never displayed to the client, dont know if that's what you want either. Note that the second Meteor.http.get is passed a callback which makes it run async .

# Shared code
Nations = new Mongo.Collection('nations')

# Server

Meteor.methods({
  getNations: function () {
    this.unblock();

    var result = Meteor.http.get('https://www.easports.com/uk/fifa/ultimate-team/api/fut/item?jsonParamObject=%7B%22page%22:1%7D');

    var totalPages = JSON.parse(result.content).totalPages;

    var callback = function(err, page) {
      if (err) 
        console.log('Cannot get page', e);
      else
        Nations.insert(page);
    }
    for (var i = 1; i < totalPages; i++) {
      Meteor.http.get('https://www.easports.com/uk/fifa/ultimate-team/api/fut/item?jsonParamObject=%7B%22page%22:' + i + '%7D', callback);
    }

    return result;
  }
});

Meteor.publish('nations', function() {
  return Nations.find();
});

# Client
Meteor.subscribe('nations');

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