[英]confusion about chaining $q promises with angular and typescript
我對Q
、 promises
、 angular
和typescript
缺乏經驗 - 所以看起來顯然明智的選擇是嘗試一起使用它們!
基本上我設置了一些方法來返回Q.IPromise<T>
以便我可以將then(f)
語句鏈接到它們上。 他們都工作得很好;
public Clear = (): Q.IPromise<IArticle> => {
var deferred = this.$q.defer();
this.$http({
url: String.format('{0}{1}', this.$settings.uri(), '/api/cancel/article'),
responseType: 'json',
method: 'GET',
withCredentials: true
}).then((response: IArticleRequest) => {
deferred.resolve(response.data.article);
}, (response) => {
deferred.reject(null);
});
return deferred.promise;
}
public Fetch = (id: string):Q.IPromise<IArticleRequestData> => {
var deferred = this.$q.defer();
this.$http({
url: String.format('{0}{1}{2}', this.$settings.uri(), '/api/articles/fetch/', id),
responseType: 'json',
method: 'GET',
withCredentials: true
}).then((response: IArticleRequest) => {
deferred.resolve(response.data);
}, (response) => {
deferred.reject(null);
});
return deferred.promise;
}
所以我可以這樣使用它們;
$articles.Fetch(1).then((r: IArticleRequestData) => {
$articles.Clear().then((n:IArticle) => {
console.log('completed!');
})
});
這很好用 - 正如我所期望的那樣。
但是現在,我需要另一個步驟——最后一次通話。 另一個then(f)
函數在最外層函數上運行,但直到最內層函數完成才發生。
簡而言之,我需要這個;
$articles.Fetch(1).then((r: IArticleRequestData) => {
$articles.Clear().then((n:IArticle) => {
// inner function completed
})
}).then((l:any)=> {
// occurs after everything else is done and inner
// functions are finished
});
我很難弄清楚如何做到這一點。 這甚至可能與承諾的工作方式有關嗎?
向內部添加另一個功能是允許的,但感覺是錯誤的方法。 如果我絕對無法弄清楚我所詢問的方式,或者我嘗試這樣做的方式是錯誤的,那么這就是我要“修復”的方法。
我想要額外的then
在外面,因為內部方法實際上負責解決某些事情,因此它們也可能分裂成其他切線或deferred
方法。
只需像這樣從內部函數返回承諾:
$articles.Fetch(1).then((r: IArticleRequestData) => {
return $articles.Clear()
}).then((l:any)=> {
// occurs after everything else is done and inner
// functions are finished
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.