我有一个调用函数的代码,在这个代码中,我返回了一个调用$http的函数。当代码运行时,我不明白为什么我看到
发出"notok“的警报,然后是"topicsRetrieve2 okay”的警报。
如果topicsRetrieve2失败了,$http不应该返回一个失败的承诺吗?
topicsRetrieve = (): any => {
this.topicsRetrieve2().then(() => {
alert("topicsRetrieve2 okay");
}, () => {
alert("topicsRetrieve2 failed");
})
}
topicsRetrieve2 = (): ng.IPromise<any> => {
return this.$http({
method: "GET",
url: "badurlxxxxxxxx"
})
.then(() => {
alert("ok");
}, () => {
alert("notok");
})AngularJS v1.4.1
更新:新的潜在解决方案:
topicsRetrieve2 = (): ng.IPromise<any> => {
var defer = this.$q.defer();
this.$http({
method: "GET",
url: "badurlxxxxxxxx"
})
.then(() => {
alert("ok");
defer.resolve();
}, () => {
alert("notok");
defer.reject()
})
return defer.promise;
}发布于 2015-09-23 17:25:27
这是用简单的话说出来的。
alert("notok")的错误回调。因此,如果您提供了一个中间错误回调("notok“),请确保为链中的后续处理程序返回新的被拒绝的承诺:
topicsRetrieve2 = (): ng.IPromise<any> => {
return this.$http({
method: "GET",
url: "badurlxxxxxxxx"
})
.then(() => {
alert("ok");
}, () => {
alert("notok");
throw new Error("notok");
})
}发布于 2015-09-23 17:25:14
你的代码有点奇怪,你想做什么?
你是在回报承诺的结果,而不是承诺本身。在topicsRetrieve2中,你想要的只是
return this.$http.get('badurlxxxx');没有.then在topicsRetrieve2内。这样,它将返回承诺,而您在topicsRetrieve中的topicsRetrieve将在成功/失败时执行
topicsRetrieve = (): any => {
this.topicsRetrieve2().then(() => {
alert("topicsRetrieve2 okay");
}, () => {
alert("topicsRetrieve2 failed");
})
}
topicsRetrieve2 = (): ng.IPromise<any> => {
return this.$http({
method: "GET",
url: "badurlxxxxxxxx"
})这将导致一个带有"topicsRetrieve2失败“的警报,假设badurlxxxxx确实返回一个non-400 :)
https://stackoverflow.com/questions/32745699
复制相似问题