Skip to content

why can not specifiy the context of the input function? #23

@dlutwuwei

Description

@dlutwuwei

When we use the mysql:

var query = thunkify(pool.query)
exports.data = function(req, res) {

    co(function*() {
        var result = yield query('select mid, name, mtype, p.....');
        var data = [];
       .....

it's always wrong with undefined property, we find that because the context of query function changed, and we change the thunkify function:

function thunkify(fn,context){
  assert('function' == typeof fn, 'function required');

  return function(){
    var args = new Array(arguments.length);
    var ctx = context||this;

    for(var i = 0; i < args.length; ++i) {
      args[i] = arguments[i];
    }
    return function(done){
      var called;

      args.push(function(){
        if (called) return;
        called = true;
        done.apply(null, arguments);
      });

      try {
        fn.apply(ctx, args);
      } catch (err) {
        done(err);
      }
    }
  }
};

so that we can use it like this:

var query = thunkify(pool.query, pool)

after all, we now can use thunkify with not-global function.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions