Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save neekey/5123473 to your computer and use it in GitHub Desktop.
Save neekey/5123473 to your computer and use it in GitHub Desktop.
在Meter.methods()中进行异步操作

相关issue: meteor/meteor#74 (comment)

方法是使用fiber模块来实现同步阻塞。

首先先利用该模块封装一个同步执行方法:

syncRun = function(func) {
    var Fiber = NodeModules.require( 'fibers' );
    var fiber = Fiber.current;
    var result, error;

    var args = Array.prototype.slice.call(arguments, 1);

    func.apply(undefined, [cb].concat(args));
    Fiber.yield();
    if (error) throw new Meteor.Error(500, error.code, error.toString());
    return result;

    function cb(err, res) {
        error = err;
        result = res;
        fiber.run();
    }
};

直接看下使用举例:

Meteor.methods({
  foo: function(){
    this.unblock();
    var myTask = function( done, num ){
      setTimeout(function(){
        done( null, num);  
      }, num );
    }
    
    return syncRun( myTask, 1000 );
  }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment