gpt4 book ai didi

javascript - 什么是显式 promise 构造反模式以及如何避免它?

转载 作者:行者123 更新时间:2023-11-28 03:56:47 25 4
gpt4 key购买 nike

我正在编写代码,其功能如下:

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构造函数反模式”,这段代码有什么不好的地方为什么这被称为 antipattern

最佳答案

deferred antipattern (now explicit-construction anti-pattern)Esailija 创造是对 Promise 不熟悉的人常见的反模式,我在第一次使用 Promise 时就自己做了。上面代码的问题是没有利用 Promise 链的事实。

Promise 可以与 .then 链接,并且您可以直接返回 Promise。您在 getStuffDone 中的代码可以重写为:

function getStuffDone(param){
return myPromiseFn(param+1); // much nicer, right?
}

Promise 的目的就是使异步代码更具可读性,并且表现得像同步代码,而不隐藏这一事实。 Promise 代表对一次性操作值的抽象,它们抽象了编程语言中的语句或表达式的概念。

您应该仅在 converting an API to promises 时使用延迟对象并且无法自动执行此操作,或者当您编写更容易以这种方式表达的聚合函数时。

引用 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.

关于javascript - 什么是显式 promise 构造反模式以及如何避免它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47498687/

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