为什么 Promise `.then` 方法的回调是一种反模式 [英] Why are Callbacks from Promise `.then` Methods an Anti-Pattern

查看:23
本文介绍了为什么 Promise `.then` 方法的回调是一种反模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 StackOverflow 上看到有人建议为 AngularJS 服务提供回调函数的答案.

I have seen answers on StackOverflow where people suggest furnishing a callback function to an AngularJS service.

app.controller('tokenCtrl', function($scope, tokenService) {
    tokenService.getTokens(function callbackFn(tokens) {
        $scope.tokens = tokens;
    });
});

app.factory('tokenService', function($http) {
    var getTokens = function(callbackFn) {
        $http.get('/api/tokens').then (function onFulfilled(response) {
            callbackFn(response.data);
        });
    };

    return {
        getTokens: getTokens
    };
});

这在我看来是一种反模式.$http 服务返回承诺,让 .then 方法执行回调函数感觉就像是一种不健康的控制反转.

This seems to me to be an Anti-Pattern. The $http service returns promises and having .then methods execute callback functions feels like an unhealthy inversion of control.

如何重构这样的代码,如何解释为什么原来的方法不是一个好主意?

How does one re-factor code like this and how does one explain why the original way was not a good idea?

推荐答案

代码可以重构如下:

app.controller('tokenCtrl', function($scope, tokenService) {
    tokenService.getTokens.then ( callbackFn(tokens) {
        $scope.tokens = tokens;
    });
});

app.factory('tokenService', function($http) {
    var getTokens = function() {
        //return promise
        return $http.get('/api/tokens').then (function onFulfilled(response) {
                //return tokens
                return response.data;
            }
        );
    };

    return {
        getTokens: getTokens
    };
});

通过让服务返回一个承诺,并使用承诺的 .then 方法,可以实现相同的功能,并带来以下好处:

By having the service return a promise, and using the .then method of the promise, the same functionality is achieved with the following benefits:

  • 承诺可以保存并用于链接.

promise 可以保存并用于避免重复相同的 $http 调用.

The promise can be saved and used to avoid repeating the same $http call.

错误信息被保留,可以使用 .catch 方法检索.

Error information is retained and can be retrieved with the .catch method.

承诺可以转发给其他客户.

The promise can be forwarded to other clients.

这篇关于为什么 Promise `.then` 方法的回调是一种反模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆