0

I have two service which depend on each other. As a consequence, I want to use promises.

Here is my code:

var defer = $q.defer();
var promiseUsers = Users.get({id: $routeParams.id});
var promiseUserFields = UserFields.get({id: $routeParams.id});
var promiseResponse = defer.promise;
$q.all([promiseUsers, promiseUserFields])
    .then(function (onFulfilled) {
        console.log(onFulfilled); // Data available
        var res = onFulfilled; // undefined
        defer.resolve([res[0].users, res[1].fields]);
    }, function(onRejected) {
        console.log(onRejected);
});
promiseResponse.then(function (data) {
    $scope.users = data[0]; // undefined
    $scope.userFields = data[1]; // undefined
    console.log($scope.users); // undefined
    console.log($scope.userFields); // undefined
});

My problem is that I can't assign an element property of the response array onFulfilled, even though I can see the console output of onFulfilled. It's kinda strange.

Any help would be greatly appreciated.

Quiy Schu
  • 1
  • 1
  • On an unrelated note, why is this different from `promiseResponse = $q.all([promiseUsers, promiseUserFields]).then(funtion(onFulfilled) { ...; return [res[0].users, res[1].fields]; });` Which is a lot less faffy (and will actually get rejected if the incoming promise fails). – George Simms Aug 07 '15 at 06:35
  • I am not quite sure if I understand you correctly. You mean that I can skip the `promiseResponse` function and put my code inside the `$q.all`? – Quiy Schu Aug 07 '15 at 06:40
  • Right, so if the `then` function returns a value, the result is a successful promise: if it throws, the result is a failed promise. – George Simms Aug 07 '15 at 06:53
  • Ok I understand. So, I can also remove the `defer`? – Quiy Schu Aug 07 '15 at 06:55
  • What output do you see for `onFulfilled`? It's likely that you just hit the wrong properties, and they ended up `undefined`. – Bergi Aug 07 '15 at 07:29
  • Btw, @GeorgeSimms is pointing out the [deferred antipattern](http://stackoverflow.com/q/23803743/1048572) – Bergi Aug 07 '15 at 07:30
  • @QuiySchu yes, exactly – George Simms Aug 07 '15 at 18:54

0 Answers0