簡體   English   中英

如何使用帶有node.lift-ed函數的when.map?

[英]How to use when.map with node.lift-ed function?

我正在學習與承諾when.js庫,並使用when.map與節點fs.readFile讓我覺得我錯過了什么。 foo promise作為單個promise可以正常工作,但是當在when.map用作映射器函數時when.map因為將索引作為第三個參數注入(然后將回調作為第4個參數傳遞)。

API文檔說, 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

有沒有更優雅的方式編寫bar函數?

我認為您誤解了partialRight函數的含義。 Lodash文檔指出了partRight

此方法類似於_.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預有功能curryRight ,你應該試試,lodash 2.4.1那里是沒有這樣的功能,所以我用啞掉:

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

順便說一句,感謝簡短,自包含,正確的例子!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM