2015-10-04 64 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'返回給客戶端 –