如何使用node.lift-ed函数when.map?

我正在学习使用when.js库的承诺,并使用带有节点fs.readFile让我觉得我错过了一些东西。 当作为一个单独的promise被调用时, foo promise可以正常工作,但是在when.map作为映射器函数使用时会失败,因为index被注入为第三个参数(然后callback被传递为第四个参数)。

API doc说when.map对mapper函数有两个参数要求。 然后,mapper函数可以写成bar ,它可以在任何情况下工作。

 var when = require('when'); var node = require('when/node'); var _ = require('lodash'); // readFile has the same signature as fs.loadFile function readFile(param1, param2, callback) { console.log(Array.prototype.slice.call(arguments)); callback(null, [param1, param2]); } var foo = _.partialRight(node.lift(readFile), 'base64'); var bar = function (fileName, index) { return node.lift(readFile)(fileName, 'base64'); }; when.map(['1', '2'], bar).done(); // works when.map(['3', '4'], foo).done(); // does not work 

有没有更优雅的方式来写barfunction?

我认为你误解了partialRight函数的意思。 Lodash文档声称partialRight

这个方法就像_.partial,除了部分参数被附加到提供给新函数的部分参数之外。

你可能认为它和curry一样,但是从右边走,但不是! 它只是将额外的参数追加到参数列表的右侧:

 function baz() { console.log(arguments) } var qux = _.partialRight(baz, 'should be second parameter, but is not') console.log(qux("first parameter", "second parameter, should be ignored, but it's not!")) 

这产生:

 { '0': 'first parameter', '1': 'second parameter, should be ignored, but it\'s not!', '2': 'should be second parameter, but is not' } 

在lodash 3.0.0-pre有函数curryRight ,你应该尝试,在lodash 2.4.1没有这样的function,所以我使用哑交换:

 var when = require('when'); var node = require('when/node'); var _ = require('lodash'); function readFile(param1, param2, callback) { console.log(Array.prototype.slice.call(arguments)); callback(null, [param1, param2]); } /* Swaps arguments of function with two arguments*/ function swap(f) { return function (a,b) { return f(b,a); } } var foo = _.curry(swap(node.lift(readFile)))("base64") var bar = function (fileName, index) { return node.lift(readFile)(fileName, 'base64'); }; when.map(['1', '2'], bar).done(); // works when.map(['3', '4'], foo).done(); // does work 

顺便说一句,感谢短,自成体系,正确的例子!