Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
dlutwuwei opened this issue Jan 15, 2016 · 2 comments
Open

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

dlutwuwei opened this issue Jan 15, 2016 · 2 comments

Comments

@dlutwuwei
Copy link

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.

@dlutwuwei
Copy link
Author

we have another solution:

var query = thunkify(pool.query).bind(pool)

@mk-pmb
Copy link

mk-pmb commented Sep 3, 2016

I'd have expected .bind() on the original function, rather than the thunk one:

var query = thunkify(pool.query.bind(pool));

… and I think the reason that there's no extra context option is precisely because you can easily .bind() your functions to any context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants