2015-10-04 38 views
0

有数据插入到Videos集合中,但future.return总是只返回空对象。如何将post _id返回给客户端?异步返回插入帖子的_id到Mongo集合

// load future from fibers 
 
var Future = Meteor.npmRequire("fibers/future"); 
 
// load fibers 
 
var Fiber = Meteor.npmRequire("fibers"); 
 
// load youtubedl 
 
var youtubedl = Meteor.npmRequire('youtube-dl'); 
 

 
Meteor.methods({ 
 
    'command' : function(line) { 
 
    // this method call won't return immediately, it will wait for the 
 
    // asynchronous code to finish, so we call unblock to allow this client 
 
    this.unblock(); 
 
    var future = new Future(); 
 
\t youtubedl.getInfo(line, function(err, stdout, stderr, videoId) { 
 
\t \t if(stdout) 
 
\t \t Fiber(function() { 
 
     \t var videoId = Videos.insert({videoObject: stdout ? stdout : stderr}); 
 
     \t console.log(videoId); 
 
     \t return videoId; 
 
      }).run(); 
 
\t \t future.return({_id: videoId}) 
 
\t }); 
 
\t return future.wait(); 
 
    } 
 
});

回答

0

您使用meteorhacks:npm还配备了异步工具,它更容易使用。 https://github.com/meteorhacks/npm#async-utilities

这里有一个例子:

// load future from fibers 
var Future = Meteor.npmRequire("fibers/future"); 
// load fibers 
var Fiber = Meteor.npmRequire("fibers"); 
// load youtubedl 
var youtubedl = Meteor.npmRequire('youtube-dl'); 

Meteor.methods({ 
    'command' : function(line) { 
    // this method call won't return immediately, it will wait for the 
    // asynchronous code to finish, so we call unblock to allow this client 
    this.unblock(); 

    var videoId = Async.runSync(function (done) { 
     youtubedl.getInfo(url, options, function (err, info) { 
      if (err) throw new Error(err); 

      var videoData = { 
       id: info.id, 
       title: info.title, 
       url: info.url //and so on... 
      }; 

      // var videoId = Videos.insert(videoData); 
      // for demo purposes we return randomIdHere 
      var videoId = "randomIdHere" 
      done(null, videoId); // when done execute this callback with any data 
     }); 
    }); 

    return videoId; 

    } 
}); 
+0

BC需要在纤维 – mhlavacka

+0

运行@mhlavacka你不必用户纤维,'Async.runSync()'将它总是会得到一个错误运行它同步示例代码是一个工作代码,它将'videoId'返回给客户端 –