异步返回已插入post的_id到Mongo collection中

Asynchronously return _id of inserted post into Mongo collection

本文关键字:id Mongo collection 返回 插入 post 异步      更新时间:2023-09-26

有数据插入到视频集合,但未来。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();
  }
});

您正在使用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;
  }
});