gpt4 book ai didi

javascript - 我应该如何在小函数之间传递数据 - 通过闭包或通过对象的属性?

转载 作者:太空宇宙 更新时间:2023-11-04 03:30:59 25 4
gpt4 key购买 nike

我有一个复杂的业务操作,例如删除用户帐户。它包含多个连接的步骤,并且必须跟踪步骤之间的某些状态。编写此操作的更好方法是什么?

我看到了很多功能性方法,如下所示。

function someAction(someParam, anotherParam, callback) {

async.waterfall([
step1,
step2,
step3,
step4
],callback
);

function step1(p,cb){/**use someParam and anotherParam here via closure*/}
function step2(p,cb){/**...*/}
function step3(p,cb){/**...*/}
function step4(p,cb){/**...*/}
};

someAction('value', 1241, (err)=>{/**...*/});

我不喜欢这种方法的是,所有内容都在单个函数的范围内定义(此处为 someAction)。

我找到了一种更加面向对象的方式,使其更具可读性。状态和 stepX 函数并不是真正私有(private)的 - 有时它方便测试。

function SomeAction(someParam, anotherParam){
//private state
this._someParam = someParam;
this._anotherParam = anotherParam;
};

SomeAction.prototype._step1 = function(p, cb){
//use this._someParam and this._anotherParam
};

SomeAction.prototype._step2 = function(p, cb){
//use this._someParam and this._anotherParam
};

SomeAction.prototype._step3 = function(p, cb){
//use this._someParam and this._anotherParam
};

SomeAction.prototype._step4 = function(p, cb){
//use this._someParam and this._anotherParam
};

//public api
SomeAction.prototype.execute = function(callback) {
async.waterfall([
this._step1,
this._step2,
this._step3,
this._step4
],callback
)
};

new SomeAction('value', 1241).execute((err)=>{/**...*/})

它们之间有性能差异吗? Node.js 中推荐的方法是什么?每次我以函数方法调用 someAction 时,所有 stepX 函数都必须从头开始定义吗?

最佳答案

您可以创建步骤函数的柯里化(Currying)版本并将它们粘贴到 waterfall 中。

function step1(arg1, arg2, cb){
// Fuction body...
}

// other steps would be defined here...

function step4(arg1, cb){
// fuction body...
}

curried_step1 = step1.bind(undefined, 'junk', 'garb');
// Other steps curried here...
curried_step4 = step4.bind(undefined, 'something');

async.waterfall([
curried_step1,
curried_step2,
curried_step3,
curried_step4
],callback
);

另一种方法可能是将数据和状态包装到一个对象中(代替真正的 monad),并使用该对象来传递您需要的内容。

关于javascript - 我应该如何在小函数之间传递数据 - 通过闭包或通过对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38009760/

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