如何确定通过 .bind() 添加的参数顺序

How to determine arguments order's added via .bind()

前言,我正在使用 BlueBird 将代码从回调重写为 Promises(顺便说一句,Bluebird 很棒),我正在尝试重构我的代码:

我有一个函数会在不同的情况下使用,这个:

var getPackagesWithIndex = function(request, indexName, indexValue){
  return new Promise(function(resolve, reject){
    Package.query(indexValue).usingIndex(indexName).exec(
      function(err, data){
        if (err) return reject(err);
        // Add the request to the payload
        data.request_ota = request;
        resolve(data);
    });
  })
}

我正在像这样链接函数以获得所需的结果:

var promote = function(request){
  var destination_build = request.params.destination_build;
  return sanitizeInput(request
    ).then(getPackagesWithIndex.bind(undefined, destination_build, 'destination_build')
    ).then(preparePackages
    ).mapSeries(updatePackage)
}

当我 console.log 结果时,参数的顺序似乎搞砸了: request 得到了 indexValue 的值,有没有办法保持有序?

bind method 的第一个参数(与 Bluebird 无关,顺便说一句)是函数调用的 this 值。不过,参数保持有序。

所以当你使用 getPackagesWithIndex.bind(undefined, destination_build, 'destination_build') 作为 then 回调时,getPackagesWithIndex 最终会被

调用
  • this undefined
  • 的上下文
  • requestdestination_build
  • 'destination_build'
  • indexName
  • 和带有承诺结果的 indexValue

如果只是移位,在前面加null之类的;如果你想要一个完全不同的顺序,你最好使用包含显式调用的函数表达式。