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.(由Esailija创造的递延反模式(现在是显式构造反模式)是对诺言做出的新手的普通反模式人,当我第一次使用诺言时,我自己就做出了。)
The problem with the above code is that is fails to utilize the fact that promises chain.(上面代码的问题是无法利用承诺链的事实。)
Promises can chain with .then
and you can return promises directly.(承诺可以与.then
,您可以直接返回承诺。)
Your code in getStuffDone
can be rewritten as:(您在getStuffDone
代码可以重写为:)
function getStuffDone(param){
return myPromiseFn(param+1); // much nicer, right?
}
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.(承诺表示对一次操作值的抽象,它们抽象出一种编程语言中的语句或表达式的概念。)
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.(仅在将API转换为Promise且无法自动执行时,或者在编写以这种方式表示的聚合函数时,才应使用延迟对象。)
Quoting Esailija:(引用Esailija:)
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.(让我们回顾一下:承诺是关于使异步代码保留同步代码的大部分丢失属性,例如平面缩进和一个异常通道。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…