![](/img/trans.png)
[英]When using Typescript, how can I do a return defer.resolve() from my code?
[英]How can I handle calling a function that returns a promise inside a defer.resolve()?
我有一个使用$ q的AngularJS函数。 在函数中,我调用了%http,在defer.resolve()
函数中,我返回了defer.resolve()
或defer.reject()
。
但是我意识到,在解决问题之前,我需要进入与this.$state.go(..)
返回承诺的状态。
所以我很困惑。 我的代码期望使用defer.resolve(),所以我该如何处理。 我可以只返回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;
}
更新
我的测试似乎表明,我确实需要按照邓肯的答案添加自己的延期。 我欢迎其他人发表评论,以证实这一点或证明我做错了。
您可以等到$state.go()
返回的承诺解决之后再解决原始的承诺:
this.$state.go('home.subjects.subject.admin.topics', {
subjectId: this.sus.subject.id
}).then(function() {
defer.resolve();
});
我将以警告作为开头。 我对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.