如何在继续之前等待异步回调方法?

时间:2017-05-02 13:21:23

标签: javascript typescript callback

我有以下两种方法。

但是在我从H​​ttp模块覆盖的get方法中,在已经执行了请求并返回响应之后调用了身份验证成功回调。这样它就可以添加  

我对promises和observables知之甚少。但是我能做些什么才能在执行请求并返回响应之前等待回调?

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);
}

1 个答案:

答案 0 :(得分:1)

您可能希望使get函数返回一个promise,因为在您进行身份验证之后,实际的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);
  });
 }
}