1

I'm making a MeteorJS app, where I fetch multiple files from remote API.

One API record can have multiple files - I want to download them, save in my Media collection and retrieve their id to store into another collection (e.g. NotMedia):

// Client side: apiArr is an array with api json objects
for(var a in apiArr){
  var pic1_id = Meteor.call('saveMedia', apiArr[a].image1_url);
  var pic2_id = Meteor.call('saveMedia', apiArr[a].image2_url);
  var collection = {
    name: apiArr[a].name,
    description: apiArr[a].desc,
    image1_id: pic1_id,
    image2_id: pic2_id
  };
  NotMedia.insert(collection);
}

my Meteor method:

//Server side:
Meteor.methods({
  saveMedia: function(media){
    var file = new FS.File();
    file.attachData(media, function(err){
      if(err){
        throw err;
      }
      file.origin_name = media;
      var id = Media.insert(file);
      return id;
    });
  },
});

But when I retrieve saved NotMedia record, image_id's are undefined. I understand that NotMedia insertion is finished faster than saving image files, but how can I synchronize that/wait for Meteor.calls to finish?

lukaszkups
  • 5,790
  • 9
  • 47
  • 85
  • 1
    You can do this using promises: http://stackoverflow.com/questions/28633187/avoiding-callback-hell-with-multiple-meteor-method-calls-on-client – Kuba Wyrobek Nov 25 '15 at 11:45

2 Answers2

0

Take a look at this: Stackoverflow && Meteor.wrapAsync

wrapAsync is what you are looking for.

Here is a quick code snippet. Hope this helps.

Meteor.methods({
  saveMedia: function(media) {
    var asyncFunc = function(arg1, arg2, callback) {
      var file = new FS.File();
      file.attachData(media, function(err) {
        if (err) {
          callback(err, null);
        }
        file.origin_name = media;
        var id = Media.insert(file);
        callback(null, id);
      });      
    };
    return Meteor.wrapAsync(asyncFunc);
  }
});
Community
  • 1
  • 1
littleStudent
  • 127
  • 1
  • 4
-2

Two things wrong here:

1) if you're using Meteor.call on a method that's defined on the server, Meteor.call will return undefined because it's calling the method asynchronously. For Meteor.call on server-side methods, you have to supply a callback function instead.

2) it looks like you're calling an asynchronous function on the server side, and you can't do that.

Meteor.methods({
  saveMedia(media) {
    let file = new FS.File();

    // this takes a callback func.. that tells me this is asynchronous - bad!
    file.attachData(media, function (err) {
      if (err) {
        throw err;
      }
      file.origin_name = media;
      return Media.insert(file);
    });
  }
});
ffxsam
  • 26,428
  • 32
  • 94
  • 144