异步将插入的帖子的_id返回到Mongo集合中

时间:2015-10-04 17:01:56

标签: javascript mongodb meteor

有数据插入到视频集中,但future.return始终只返回空对象。如何将post _id返回给客户?



// 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();
	youtubedl.getInfo(line, function(err, stdout, stderr, videoId) {
		if(stdout)
		  Fiber(function() {
        	var videoId = Videos.insert({videoObject: stdout ? stdout : stderr});
        	console.log(videoId);
        	return videoId; 
          }).run();
		future.return({_id: videoId})
	});
	return future.wait();
  }
});




1 个答案:

答案 0 :(得分:0)

您正在使用meteorhacks:npm它还附带Async工具,它更易于使用。 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;

  }
});