[英]How can I handle calling a function that returns a promise inside a defer.resolve()?
I have an AngularJS function that uses $q. 我有一个使用$ q的AngularJS函数。 In the function I have a call to %http and in the .then functions I return
defer.resolve()
or defer.reject()
. 在函数中,我调用了%http,在
defer.resolve()
函数中,我返回了defer.resolve()
或defer.reject()
。
However I realized that before the resolve I need to go to a different state which I do with this.$state.go(..)
which returns a promise. 但是我意识到,在解决问题之前,我需要进入与
this.$state.go(..)
返回承诺的状态。
So I am confused. 所以我很困惑。 My code is expecting a defer.resolve() so how do I handle this.
我的代码期望使用defer.resolve(),所以我该如何处理。 Can I just return
this.$state.go(...)
? 我可以只返回
this.$state.go(...)
吗?
topicDeleteSubmit = (): ng.IPromise<any> => {
var self = this;
var defer = self.$q.defer();
self.$http({
url: self.url,
method: "DELETE"
})
.then(
(response: ng.IHttpPromiseCallbackArg<any>): any => {
// Original code
this.$state.go('home.subjects.subject.admin.topics', {
subjectId: this.sus.subject.id
});
defer.resolve();
// New code
return this.$state.go('home.subjects.subject.admin.topics', {
subjectId: this.sus.subject.id
});
},
(error): any => {
defer.reject(error);
}
)
return defer.promise;
}
Update 更新
My tests seem to show that I do need to add my own defer in the way of Duncan's answer. 我的测试似乎表明,我确实需要按照邓肯的答案添加自己的延期。 I would welcome comments from others confirming this or proving me wrong.
我欢迎其他人发表评论,以证实这一点或证明我做错了。
You can wait until the promise returned by $state.go()
resolves before resolving the original promise: 您可以等到
$state.go()
返回的承诺解决之后再解决原始的承诺:
this.$state.go('home.subjects.subject.admin.topics', {
subjectId: this.sus.subject.id
}).then(function() {
defer.resolve();
});
I'll preface my answer with a caveat. 我将以警告作为开头。 I don't have a lot of knowledge of angularjs, but I do know promises pretty well.
我对angularjs并不了解很多,但是我确实知道promise。
topicDeleteSubmit = (): ng.IPromise<any> => {
// Not bothering with 'self'; properly-compiled arrow functions () => should
// inherit `this`.
return this.$http({
url: this.url,
method: "DELETE"
})
.then(
(response: ng.IHttpPromiseCallbackArg<any>): any => {
return this.$state.go('home.subjects.subject.admin.topics', {
subjectId: this.sus.subject.id
});
}
// by not including an error handler, the method that calls this one
// will need to resolve any errors. Any low-level errors will copy
// over to the promise that expects their result. (similar to
// exception handling)
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.