Search code examples
google-authenticationgoogle-api-js-client

GoogleAuth library loading with promises


I am trying to load google authentication library using promises, but I fail when I try to call gapi.auth2.getAuthInstance() and return it in promise;

Here's how I am doing this:

var loadPlatform = function ($q) {
    var deferred = $q.defer(),
        platform = document.createElement('script');

    platform.src ='https://apis.google.com/js/platform.js';
    platform.type = 'text/javascript';
    platform.async = true;
    platform.defer = true;
    platform.onload = deferred.resolve;
    platform.onerror = deferred.reject;

    document.body.appendChild(platform);

    return deferred.promise;
};

//I return this from other function
return loadPlatform($q)
    .then(function () {
        var deferred = $q.defer();

        gapi.load('auth2', function () {
            deferred.resolve(gapi.auth2);
        });

        return deferred.promise;
    })
    .then(function (auth2) {
        //This function retuns Promise
        //https://developers.google.com/identity/sign-in/web/reference#gapiauth2initparams
        return auth2.init(params);
    })
    .then(function (GoogleAuth) {
        //Here I should have solved GoogleAuth object
    });

Everything works until I return auth2.init(params) then browser freezes. What's happening here?


Solution

  • I just experienced the same issue.

    It seems like you can't chain the init() promise of the auth2 object.

    I had to wrap around it to avoid the browser freeze.

    return new Promise<void>(resolve => {
      gapi.auth2.init({
        client_id: this._clientId,
        scope: 'profile'
      }).then(() => resolve());
    })
    

    Also it was interesting that I could not apply the resolve function directly.

    .then(resolve);
    

    Update

    As said above, the returned object of the init() call is not a promise, it is kind of a wrapper and only returns a real promise once you called the .then method

    enter image description here

    return gapi.auth2.init({
      client_id: this._clientId,
      scope: 'profile'
    }).then(); 
    // Auth2 only returns a promise, when we chained into the PromiseLike object once.