什么是明确的承诺构建反模式,我该如何避免它?
我编写的代码看起来像:
I was writing code that does something that looks like:
function getStuffDone(param) { | function getStuffDone(param) {
var d = Q.defer(); /* or $q.defer */ | return new Promise(function(resolve, reject) {
// or = new $.Deferred() etc. | // using a promise constructor
myPromiseFn(param+1) | myPromiseFn(param+1)
.then(function(val) { /* or .done */ | .then(function(val) {
d.resolve(val); | resolve(val);
}).catch(function(err) { /* .fail */ | }).catch(function(err) {
d.reject(err); | reject(err);
}); | });
return d.promise; /* or promise() */ | });
} | }
有人告诉我这称为延迟反模式或者 承诺
构造函数反模式,这段代码有什么不好,为什么这叫做反模式?
Someone told me this is called the "deferred antipattern" or the "Promise
constructor antipattern" respectively, what's bad about this code and why is this called an antipattern?
deferred antipattern(now explicit-construction anti-pattern)由 Esailija 创造的是一个普通的反模式的人,他们是新的承诺,我自己做的就是当我第一次使用承诺。上述代码的问题在于无法利用promises chain的事实。
The deferred antipattern (now explicit-construction anti-pattern) coined by Esailija is a common anti-pattern people who are new to promises make, I've made it myself when I first used promises. The problem with the above code is that is fails to utilize the fact that promises chain.
Promise可以与链接.then
你可以直接退还承诺。您在 getStuffDone
中的代码可以重写为:
Promises can chain with .then
and you can return promises directly. Your code in getStuffDone
can be rewritten as:
function getStuffDone(param){
return myPromiseFn(param+1); // much nicer, right?
}
Promise是关于使异步代码更具可读性并且表现得像同步代码而不隐藏那个事实。 Promise表示对一次操作值的抽象,它们用编程语言抽象语句或表达式的概念。
Promises are all about making asynchronous code more readable and behave like synchronous code without hiding that fact. Promises represent an abstraction over a value of one time operation, they abstract the notion of a statement or expression in a programming language.
你应该只使用延迟对象将API转换为承诺并且可以'自动执行,或者当您编写以这种方式更容易表达的聚合函数时。
You should only use deferred objects when you are converting an API to promises and can't do it automatically, or when you're writing aggregation functions that are easier expressed this way.
引用Esailija:
Quoting Esailija:
这是最常见的反模式。当你不真正理解承诺并将它们视为美化事件发射器或回调实用程序时,很容易陷入这种情况。让我们回顾一下:promises是关于使异步代码保留同步代码的大部分丢失属性,例如扁平缩进和一个异常通道。
This is the most common anti-pattern. It is easy to fall into this when you don't really understand promises and think of them as glorified event emitters or callback utility. Let's recap: promises are about making asynchronous code retain most of the lost properties of synchronous code such as flat indentation and one exception channel.