承诺chain/general代码convention/style
Promise chain/general code convention/style
有一些 promise 约定的最佳实践可以作为参考。
我的意思是当你写的时候你可以这样做
step1().then(step2()).then(retur ...step3())
.catch(function(err) {
console.log(err)
;});
但我认为更可读的方式是这样的
step1()
.then(function() {
return step2();
}).then(function() {
return step3()
}).catch(function(err) {
log(err);
});
有一些官方建议如何在可读性等方面更好地编写它...
如果您已经准备好连接方法,则创建中间闭包没有任何好处。
你的两个例子也在做完全不同的事情。您的第一个示例应如下所示。
step1()
.then(step2)
.then(step3)
.catch(function(err) {
console.log(err)
;});
我不认为这有什么不妥。这也将使您的堆栈跟踪也更具可读性。
这是因为,在此示例中,您有一堆中间匿名函数。
因此,堆栈跟踪将包含对那些匿名函数的引用,而它们没有任何价值。
step1()
.then(function(val) {
return step2(val);
}).then(function(val) {
return step3(val)
}).catch(function(err) {
log(err);
});
为了防止匿名混乱,您可能希望像这样命名所有匿名方法。
step1()
.then(function _step2(val) {
return step2(val);
}).then(function _step3(val) {
return step3(val)
}).catch(function(err) {
log(err);
});
我在它们前面加了下划线作为前缀,因为它们不能与我们调用的实际方法同名。
这是一堆重复,没有多大意义,因为 _step2 和 step2 函数完全相同。
另请注意,在您的首选示例中,您没有正确传递参数,我也在上面添加了该逻辑,如您所见,这进一步增加了噪音。
有一些 promise 约定的最佳实践可以作为参考。
我的意思是当你写的时候你可以这样做
step1().then(step2()).then(retur ...step3())
.catch(function(err) {
console.log(err)
;});
但我认为更可读的方式是这样的
step1()
.then(function() {
return step2();
}).then(function() {
return step3()
}).catch(function(err) {
log(err);
});
有一些官方建议如何在可读性等方面更好地编写它...
如果您已经准备好连接方法,则创建中间闭包没有任何好处。 你的两个例子也在做完全不同的事情。您的第一个示例应如下所示。
step1()
.then(step2)
.then(step3)
.catch(function(err) {
console.log(err)
;});
我不认为这有什么不妥。这也将使您的堆栈跟踪也更具可读性。
这是因为,在此示例中,您有一堆中间匿名函数。 因此,堆栈跟踪将包含对那些匿名函数的引用,而它们没有任何价值。
step1()
.then(function(val) {
return step2(val);
}).then(function(val) {
return step3(val)
}).catch(function(err) {
log(err);
});
为了防止匿名混乱,您可能希望像这样命名所有匿名方法。
step1()
.then(function _step2(val) {
return step2(val);
}).then(function _step3(val) {
return step3(val)
}).catch(function(err) {
log(err);
});
我在它们前面加了下划线作为前缀,因为它们不能与我们调用的实际方法同名。
这是一堆重复,没有多大意义,因为 _step2 和 step2 函数完全相同。
另请注意,在您的首选示例中,您没有正确传递参数,我也在上面添加了该逻辑,如您所见,这进一步增加了噪音。