gpt4 book ai didi

javascript - 成功时拒绝 $http promise

转载 作者:搜寻专家 更新时间:2023-11-01 04:56:54 24 4
gpt4 key购买 nike

我有一个返回 $http GET promise 的函数( promise 成功/错误由调用者处理)。我需要的是,给定某些条件,即使 $http 成功,也返回错误(调用者会将此条件捕获为被拒绝的 promise )。

在这个 plunk 中,我试图返回 $q.reject() 但这不起作用。

http://plnkr.co/edit/iC3Wb1PBUFrXgPbTJyU0?p=preview

这是 JavaScript:

app.controller("ctrl", function($scope, $http) {
var getUrl = function() {
var config = {
method: 'GET',
url: 'some.txt'
};
var x = 1; // if x == 1 the http should fail
return $http(config).success(function(response, status, headers, config) {
console.log(response);
if (x == 1) return $q.reject('error');
}).error(function(data, status, headers, config) {});
};
var init = function() {
var promise = getUrl();
promise.then(function() {
alert('OK');
}, function() {
alert('error');
});
};
init();
});

有什么想法吗?

最佳答案

$http.success()error() 是并非 100% 符合 promise 的便捷快捷方式。使用 vanilla promise then 代替:

$http(config).then(function(response){return $q.reject}, function onError(reason){})

updated plunker

关于javascript - 成功时拒绝 $http promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28076258/

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