gpt4 book ai didi

javascript - 如何在保持 DRY 的同时处理 javascript 中的条件回调?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:04:56 25 4
gpt4 key购买 nike

我最近一直在玩 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...这样代码可能真的很臃肿...

那么有没有一个漂亮的忍者技巧可以解决这个问题?

最佳答案

好吧,一行代码并没有那么重复,但如果你做的不止于此,它就会变得非常不枯​​燥。将您的最终逻辑包装到一个函数中,然后在您的条件语句中调用它怎么样?

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();
}

关于javascript - 如何在保持 DRY 的同时处理 javascript 中的条件回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11124057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com