问题描述
我正在编写的代码看起来像:
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() */ | });
} | }
有人告诉我这分别称为延迟反模式"或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?
推荐答案
Esailija 创造的"rel="noreferrer">延迟反模式(现在是显式构造反模式) 是一个常见的反模式人,对 promises 不熟悉,当我第一次使用 promises 时,我自己做了.上面代码的问题是没有利用promise链这一事实.
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
链接,您可以直接返回 Promise.您在 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?
}
Promises 就是为了让异步代码更具可读性,并且在不隐藏这一事实的情况下表现得像同步代码.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 转换为 promises 并且不能自动执行,或者当您编写更容易以这种方式表达的聚合函数时.
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.
引用 Esalija:
Quoting Esailija:
这是最常见的反模式.当您并不真正理解 Promise 并将它们视为美化的事件发射器或回调实用程序时,很容易陷入这种困境.让我们回顾一下:promise 是关于让异步代码保留同步代码丢失的大部分属性,例如扁平缩进和一个异常通道.
这篇关于什么是显式承诺构造反模式,我该如何避免它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!