【问题标题】:(Angular)Js - how to simplify promise result?(Angular)Js - 如何简化承诺结果?
【发布时间】:2019-03-31 08:50:22
【问题描述】:

我来自嵌入式 C 背景,并且在 AngularJs 1.x 中自学成才;我怀疑我的问题是一个通用的 JS 问题,而不是 AngularJs 特定的问题。

我发现这种模式在我的代码中重复出现:

                $http.get(url)
                    .success(function(data, status, headers, config)
                    {
                       console.log('Success');
                    });

               })
                .error(function(data, status, headers, config)
                {
                    console.error('Error !');
                });

作为一个 C 人,我不喜欢 lambda,尽管我对回调很满意。

成功和失败部分的代码可能非常大,这会使代码看起来很混乱——尤其是看到所有这些代码都作为参数传递。

我猜$http 的参数是(a)promise(s)。

有没有什么方法可以让代码更模块化,更容易阅读和维护?

例如,我想我可以声明一些成功/失败函数并调用它们,类似于:

function it_succded(data, status, headers, config))
{
    console.log('Success');
});

function it_failed(data, status, headers, config)
{
    console.error('Error !');
});

$http.get(url)
.success(function(data, status, headers, config)
 {
     it_succded(data, status, headers, config))
   });
})
.error(function(data, status, headers, config)
 {
    it_failed(data, status, headers, config)
  });
});

当然,我可以编写代码并查看,但在这里提问是因为我想学习,并希望得到真正了解这一点的人的解释,最好是专业编写 (Angular)Js 代码的人。

【问题讨论】:

  • docs.angularjs.org/api/ng/service/$http; $http 方法 return 承诺,参数有一个字符串。我不知道成功和失败的方法是什么,promise 有 then 和 catch。这些参数是回调函数,是的,您可以提取它们(但是function(args) { callback(args); } 除了吞下任何返回值之外没有其他任何作用;只需传递callback)。
  • .success 语法在 Angular v1.4.3 之前是正确的。在此处查看旧文档:code.angularjs.org/1.4.3/docs/api/ng/service/$http

标签: javascript angularjs promise angular-promise


【解决方案1】:

对于使用promise接口,你不应该使用.success().error():它们是deprecated。而是使用.then()catch()。这些回调接收的参数略有不同:

$http.get(url).then(function(response) {
     console.log("Success", response.data);
}).catch(function(response) {
     console.log("Error", response.status);
});

response 是一个具有预期 properties 的对象:

  • data{string|Object} – 使用转换函数转换的响应正文。
  • status{number} – 响应的 HTTP 状态代码。
  • headers{function([headerName])} – 标头获取函数。
  • config{Object} – 用于生成请求的配置对象。
  • statusText{string} – 响应的 HTTP 状态文本。
  • xhrStatus{string} – XMLHttpRequest 的状态(完成、错误、超时或中止)。

您确实可以单独定义回调函数,然后您的回调参数可以只是函数引用:

function it_succded(response) {
     console.log("Success", response.data);
}
function it_failed(response) {
     console.log("HTTP Error", response.status, response.statusText);
}
$http.get(url).then(it_succded).catch(it_failed);

您可以将这些函数定义为方法,例如在$scope 对象上:

$scope.it_succded = function (response) {
     console.log("Success", response.data);
     $scope.data = response.data;
}
$scope.it_failed = function (response) {
     console.log("HTTP Error", response.status, response.statusText);
}
$http.get(url).then($scope.it_succded).catch($scope.it_failed);

小提示:请注意,当 Promise 实现调用这些回调时,this 不会被设置。所以要么不要在其中使用this,要么将它们定义为箭头函数(this 将是词法上下文中的任何内容),将函数绑定到特定的this 对象,或者提供很少的包装回调:

.then(function(response) { 
     return $scope.it_succded(response);
})

【讨论】:

  • 看起来我猜对了,但很高兴得到如此高代表的用户的确认。谢谢。我会 24 小时开放,以吸引其他答案,帮助像我这样的其他 n00bs,然后奖励答案
  • 我不认为您可以更新您的答案以将 it_succdedit_failed 声明为 $scope 函数?
  • 你的问题确实是一个通用的 JS 问题(简化了 Promise 回调),所以把它与 AngularJS 概念联系起来似乎不对?
  • Angular 1 中唯一可能不支持的是解构(我们现在是版本 7),所以不要这样做 function ({data, status}),而是 function (response)。并解决response.data,...等属性。我更新了我的答案以使用该语法。
  • 有几种可能,看你的实际情况。例如,可以使用bind。请注意,Promise 实现将使用一个额外的参数(响应)调用该函数。如果您对此有特定问题,但找不到答案,请考虑发布一个新问题。
【解决方案2】:

是的,你可以。

$http({
your configs
})
.then(funtion(result){ // function on success
   return result.data // this is important as AngularJS $http will bind the data from the server into this variable
},
function(errorResponse){
if(errorResponse.status === 401){
    // your code for handling 401 errors
}
else if(errorResponse.status === 404){
    // your code for handling 404 errors
}
else if(errorResponse.status === 500){
    // your code for handling 500 errors
}
})
.then(function(data){
    // another function to process data
    return data
})
.then(function(data){
    // yet another function to process data
    return data
})

我们可以根据需要组合尽可能多的 then 回调。 你可以从这个链接阅读更多关于承诺的信息:https://scotch.io/tutorials/javascript-promises-for-dummies

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 2016-06-21
    • 2015-11-27
    • 2017-08-14
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2021-05-04
    • 2014-02-02
    相关资源
    最近更新 更多