相关疑难解决方法(0)

使用带有参数数组的Function.prototype.bind?

如何使用参数数组调用Function.prototype.bind,而不是硬编码参数?(不使用ECMA6,因此没有传播运营商).

我试图在使用回调的模块周围放置一个promises包装器,我想绑定传递给我的包装器方法的所有参数并绑定它们.然后我想用我自己的回调调用部分应用的绑定函数,它将解析或拒绝一个promise.

var find = function() {
  var deferred, bound;
  deferred = Q.defer();
  bound = db.find.bind(null, arguments);
  bound(function(err, docs) {
    if(err) {
      deferred.fail(err);
    } else {
      deferred.resolve(docs);
    }
  });
  return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)

但显然这不起作用,因为bind需要参数而不是参数数组.我知道我可以通过将我的回调插入到arguments数组的末尾并使用apply来做到这一点:

arguments[arguments.length] = function(err, docs) { ... }
db.find.apply(null, arguments);
Run Code Online (Sandbox Code Playgroud)

或者通过遍历arguments数组并为每个参数重新绑定函数:

var bound, context;
for(var i = 0; i < arguments.length; i++) {
   context = bound ? bound : db.find;
   bound = context.bind(null, arguments[i]);
}
bound(function(err, docs) { ... })
Run Code Online (Sandbox Code Playgroud)

但这两种方法都很脏.有任何想法吗?

javascript functional-programming partial-application promise

47
推荐指数
3
解决办法
1万
查看次数