我有以下2種方法。如何在繼續之前等待異步回調方法?
但是,在我從Http模塊重寫的get
方法中,認證成功回調在它已經執行請求並返回響應之後被調用。這樣它就會將JWT標記以錯誤的順序添加到標題中,並且太晚了。
我不是承諾和觀測超級懂行的。但我能做些什麼,以便它實際上是回調等待執行的請求,並返回響應之前完成?
authenticate(authCompletedCallback, errorCallback) {
let authContext = new Microsoft.ADAL.AuthenticationContext(AUTHORITY_URL);
authContext.tokenCache.readItems().then((items) => {
if (items.length > 0) {
AUTHORITY_URL = items[0].authority;
authContext = new Microsoft.ADAL.AuthenticationContext(AUTHORITY_URL);
}
// Attempt to authorize user silently.
authContext
.acquireTokenSilentAsync(RESOURCE_URL, CLIENT_ID)
.then(authCompletedCallback,() => {
// We require user credentials so trigger authentication dialog.
authContext
.acquireTokenAsync(RESOURCE_URL, CLIENT_ID, REDIRECT_URL)
.then(authCompletedCallback, errorCallback);
});
});
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
this.authenticate((authResponse) => {
// This is executed second.
if (!options) {
options = { headers: new Headers() };
}
options.headers.set('Authorization', 'Bearer ' + authResponse.accessToken);
}, (err) => {
alert(JSON.stringify(err));
});
// This is executed first.
return super.get(url, options);
}
見http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Saravana