1

I need to run two nested async functions and return callback from the second one to the client. future.return doesn't work inside Fibers. How to return result to the client without using collections?

Meteor.methods({
    'youtube':function(object) {

    var youTube = new YouTube();

    youTube.search(object.song, 1, function(error, result) {
      if (error) {
        console.log(error);
      }
      else {
        Fiber(function() {

          var future = new Future();

          ytdl.getInfo(result.url, function(err, result) {
            future.return({data: result});
          });

          return future.wait();

        }).run();

      }
    });
});
mhlavacka
  • 691
  • 11
  • 25

1 Answers1

2

Future should be returned in first method scope. And read about Meteor.bindEnvironment

var Future = Npm.require('fibers/future');
var bound  = Meteor.bindEnvironment(function(callback){ return callback(); });
Meteor.methods({
  'youtube':function(object) {
    var fut = new Future();
    var youTube = new YouTube();

    youTube.search(object.song, 1, function (error, result) {
      bound(function () {
        if (error) {
          console.log(error);
        } else {
          ytdl.getInfo(result.url, function(err, result) {
            fut.return({data: result});
          });
        }
      });
    });
    return fut.wait();
  }
});
dr.dimitru
  • 2,645
  • 1
  • 27
  • 36
  • Thanks for your answer, I didn't know about bindEnviroment. I wonder how would it work with an array of results coming from the first async function (multiple search results in youTube.search function). tried to implement it using this example - https://gist.github.com/joscha/4130605. But can't wrap my head around how it works with bindEnviroment together – mhlavacka Jan 17 '16 at 17:48
  • you just execute `fut.return()` once right when you need to return data. For example if you're traversing thru some array, just return data after array is ended. – dr.dimitru Jan 17 '16 at 19:43
  • About `bindEnviroment` - it is uses "magic" C code inside `Fibers` (separate huge topic to discuss). So, only thing you need to know about it - use in all non-Meteor async callbacks, because all Meteor's async callback already wrapped into `bindEnviroment`. – dr.dimitru Jan 17 '16 at 19:46