使用wrapAsync完成内部函数后,如何使Meteor Method返回结果?

时间:2016-01-02 10:10:43

标签: javascript asynchronous meteor async-await

我有Meteor方法,下面有一个片段(下面),里面有异步循环。据我所知,这应该用meteor wrapAsync包装,但是他们的文档对我来说不够清楚,所以我不确定如何正确实现它。在这个例子中使用wrapAsync最简单的方法是什么?

if(Meteor.isServer){

  Meteor.methods({
    listCollections: function(){

      // list collections in database
      db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
      collections = db.listCollections();

      // convert cursor with collections to javascript array:

      // method should wait for this loop to finish before returning result
      var collectionsArray = [];
      collections.each(function(n, collection){
          if(collection){
              collectionsArray.push(collection.name);
          }
      });

      // return ignores the each loop and empty array is passed as a result
      return collectionsArray;

    }
  });

  Meteor.call("listCollections", function(err, res){
    console.log(res);
  });

}

2 个答案:

答案 0 :(得分:0)

从您的上下文中很难理解,但通常wrapAsync可以像这样使用

Meteor.methods({ 
    'yourCurrentMethod': function(sentCollections) {
        var processArray = function (collections) {
            var collectionsArray = [];

            collections.each(function(n, collection){
                if(collection){
                    collectionsArray.push(collection.name);
                }
            });

            // return ignores the each loop and empty array is passed as a result
            return collectionsArray;  
        };

        var processArrayCalling = Meteor.wrapAsync(processArray);
        var result = processArrayCalling(sentCollections); 

        // process with the result
    }
});

答案 1 :(得分:0)

我使用Future解决了这个问题,这非常容易使用。

if(Meteor.isServer){

  var Future = Npm.require( 'fibers/future' ); // future code

  Meteor.methods({
    listCollections: function(){

      // list collections in database
      db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
      collections = db.listCollections();

      // create our future instance
      var future = new Future(); // future code

      // count number of collections inside collection list
      var collectionsCount = 0;
      collections.each(function(n, collection){
        collectionsCount++;
      });

      // method should wait for this loop to finish before returning result
      var collectionsArray = [];
      var i = 0;
      collections.each(function(n, collection){
        if(collection){
            collectionsArray.push(collection.name);
        }
        i++;
        if( i == collectionsCount ){
          future.return( collectionsArray ); // future code
        }
      });

      return future.wait(); // future code
    }
  });

  Meteor.call("listCollections", function(err, res){
    console.log(res);
  });

}