2017-05-02 207 views
-1

我有以下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); 
} 
+0

見http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Saravana

回答

1

你可能想使get函數返回一個承諾,因爲實際Response對象不應該存在,直到您通過身份驗證後。不過,看起來你正在重寫一個方法,所以也許你會想做出一個不同的方法。

getWithAuthentication(url: string, options?: RequestOptionsArgs): Promise<Observable<Response>> { 
return new Promise((resolve, reject) => { 
    this.authenticate((authResponse) => { 
    if (!options) { 
     options = { headers: new Headers() }; 
    } 

    options.headers.set('Authorization', 'Bearer ' + authResponse.accessToken); 
    let response = super.get(url, options); 
    resolve(response); 
    }, (err) => { 
    alert(JSON.stringify(err)); 
    reject(err); 
    }); 
} 
} 
+0

因此,而不是調用'http.get()' ,我現在要調用'http.getWithAuthentication()。then()'? –

+0

是的,這就是主意。或者如果你想使用異步代碼,你可以使用await。 – libertyernie