4

我最近一直在玩,NodeJS我发现自己遇到了一个常规模式问题:

我有一个主要操作正在运行,取决于一些配置参数,我需要执行一个额外的步骤,但这个步骤是异步的:

    if(request.config.save) {

        fs.writeFile(request.config.save, decryptedData, function(err) {
            // Continue the operation with a callback...
            // Perform some other ops.
            if(typeof callback == 'function') callback(decryptedData);
        }.bind(this));

    } else {

        // Continue the same operation without a callback
        // Perform some other ops.
        if(typeof callback == 'function') callback(decryptedData);

如您所见,此代码不是 DRY,因为主结尾(回调)被调用了两次。

我看到的唯一方法是使用函数(但函数调用又不是 DRY ......而且代码可能真的很臃肿......

那么有一个漂亮的忍者技巧来解决这个问题吗?

4

2 回答 2

4

好吧,一行代码并不是那么重复,但如果你做的不止这些,它会变得非常不枯​​燥。将你的最终逻辑包装到一个函数中,然后在你的条件中调用它呢?

var endTick = function(){
    if(typeof callback == 'function') callback(decryptedData);
}

if(request.config.save) {

    fs.writeFile(request.config.save, decryptedData, function(err) {
        // Continue the operation with a callback...
        // Perform some other ops.
        endTick();
    }.bind(this));

} else {

    // Continue the same operation without a callback
    // Perform some other ops.
    endTick();
}
于 2012-06-20T16:38:03.440 回答
0
function cb() {
   if (typeof arguments[0] === 'function')
      arguments[0].apply(null, Array.prototype.slice.call(arguments,1));
}

Shouldn't be more than around 10 characters longer (might have to bind) than a normal function call without the typeof check, and assuming no bind it shouldn't be more than 4.

There is no way to solve this without paying some price, somewhere.

于 2012-06-20T16:43:15.463 回答