I have an AngularJS function that uses $q. In the function I have a call to %http and in the .then functions I return defer.resolve()
or 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.
So I am confused. My code is expecting a defer.resolve() so how do I handle this. Can I just return 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:
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.
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)
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.