Alon Shmiel
Alon Shmiel

Reputation: 7121

Promise: then is not defined (asynchronous call)

I am trying to fill $scope.data with the data that I get from:

function getUserData(callback) {
    FB.api('/me/friends', function (response) {
        if (callback) return callback(response.data);
        return response.data;
    });
}

Because it's an asynchronous call, I am using promise in order to fill it.

This method is found in my controller:

Typekit.GetData().then(function (data) {
     $scope.data = data;
});

This is my factory:

App.factory('TypekitService', ['$http', '$q', function ($http, $q) {
      return {
          GetData: function () {
               return getUserData(callback);
               function callback(data) {
                   var deferred = $q.defer();
                   deferred.resolve(window.userRates);
                   return deferred.promise;
               }
          }
      }
}]);

Unfortunately, I get:

Cannot read property 'then' of undefined

Any help appreciated!

Upvotes: 0

Views: 4445

Answers (3)

MBielski
MBielski

Reputation: 6620

You are referring to your service with Typekit but it is exposed by your factory as TypekitService.

Upvotes: 0

aseferov
aseferov

Reputation: 6403

its because getUserData doesnt return promise

function getUserData(callback) {
    return FB.api('/me/friends', function (response) {
        if (callback) return callback(response.data);
        return response.data;
    });
}

or

function getUserData(callback) {
    var p = $q.defer()
    FB.api('/me/friends', function (response) {
        if (callback) return callback(response.data);
        p.resolve(response.data)
    });
    return p.promise
}

Upvotes: 2

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40328

As it is, the promise will be created when the data has actually been returned. Try something along the lines of:

GetData: function () {
     var deferred = $q.defer();
     getUserData(function(data) {
         deferred.resolve(data);
     });
     return deferred.promise;
}

This way you return the promise (so GetData(...).then() is defined) and only resolve the promise in the callback.

Upvotes: 1

Related Questions