async.apply在async.waterfall中 [英] async.apply inside async.waterfall
问题描述
我有以下代码片段
async.waterfall([
// Read directory
async.apply(fs.readdir, '../testdata'),
// Load data from each file
function(files, callback) {
async.each(files, loadDataFromFile, callback);
}
], function(err) {
if (err) {
api.logger.error('Error while inserting test data', err);
}
next();
});
有没有办法可以替换这件作品:
Is there a way I could replace this piece:
function(files, callback) {
async.each(files, loadDataFromFile, callback);
}
只有一个功能?就像我上面所做的那样,使用 async.apply()
我将其替换为:
with just a function? Like I did above, using async.apply()
I replaced this:
function(callback) {
fs.readdir('../testdata', callback);
}
我知道我可以创建自己的帮助函数来做到这一点,或者我可以保持这样,但我想知道是否有办法只使用 .bind()
或 .apply()
。
I know I could create my own helper function to do this, or I can leave it like this, but I was wondering if there's a way to do this using only functions like .bind()
or .apply()
.
我考虑过使用 .bind()
然后 .apply()
但这会导致函数(loadDataFromFile,files,callback)
这是不行的。
I've thought about using .bind()
then .apply()
but this would result in function(loadDataFromFile, files, callback)
which is not okay.
推荐答案
我想知道是否有办法只使用.bind()或.apply()这样的函数。
I was wondering if there's a way to do this using only functions like .bind() or .apply().
似乎不仅使用本机函数,或仅使用来自 async
的函数。正如您所注意到的,需要翻转
每个
函数。部分应用程序的某些实现(如Underscore)允许使用中间参数,但您需要显式包含它们。
Not using only native functions, or only those from async
it seems. As you have noticed, one would need to flip
the each
function. Some implementations of partial application (like Underscore) allow intermediate arguments, but you would need to explicitly include them.
async.waterfall([
_.partial(fs.readdir, '../testdata'), // Read directory
_.partialRight(async.each, loadDataFromFile), // Load data from each file
], function(err) {
if (err)
api.logger.error('Error while inserting test data', err);
next();
});
可能你需要 bind
方法但是,正确的上下文,如 fs.readdir.bind(fs,'.. / testdata')
。
Possible you will need to bind
the method to the correct context though, like fs.readdir.bind(fs, '../testdata')
.
这篇关于async.apply在async.waterfall中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!