0

I know this is probably an easy question to answer but I just cannot get my head around it. I need a function that increments a number by 1 and returns a promise.

Here is a fiddle

Failed Example

var incrementingFn = function() {

  return $q(function(resolve,reject) {
    var n = 0;

    $q.resolve(function() {
      n += 1;
      return n;
    }()); 
    }
}


incrementingFn().then(function(res) {
  var num = res;
}
tester123
  • 1,033
  • 2
  • 12
  • 17

2 Answers2

0

There are many incorrect things you are doing in code.

Here is list of them.

  1. Using too old angular reference, use the latest one.
  2. Your controller should binded to the module which you have created. Detail explanation here
  3. You were misssed to closed the closing bracket } while doing resolve.
  4. And number declaration should be there outside function, as @charlietfl said.

Code

var myApp = angular.module('myApp', []);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.controller('MyCtrl', MyCtrl)

function MyCtrl($scope, $q) {
  $scope.name = 'Superhero';
  var n = 0;
  var incrementingFn = function() {

    return $q(function(resolve, reject) {


      resolve(function() {
        n += 1;
        return n;
      }());
    })
  }

  incrementingFn().then(function(res) {
      $scope.num = res;
    }
  );
}

Working Fiddle

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

You have syntax problems as well as other logic problems in your code

Try

 var n = 0;

  var incrementingFn = function() {
    return $q(function(resolve, reject) {
      n++;
      resolve(n);    
    });
  }

  incrementingFn().then(function(res) {
    $scope.num = res;
  });

One main point is if you plan to increment the number again you don't want to declare it as 0 inside the function each time or it will always return 1

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150