-1

In my application, a user clicks a button which triggers runsOnClick. In runsOnClick, I try to use a promise to call someFunc (this happens as expected) and once someFunc has finished running, I'm expecting this code (the then part of the promise) inside runsOnClick to run but it never does

then(function() {
          console.log("in runsOnClick");//this never runs, why?
         });

How do I structure a promise so that all the code in runsOnClick runs?

  $scope.someFunc = function(){
    console.log("in someFunc");
    $http.get('http://localhost:8090/endpoint').success(function(data){
      console.log(data, "this logs");
      });
  },
  $scope.runsOnClick = function(){

     $scope.someFunc().then(function() {
      console.log("in runsOnClick");//this never runs, why?
     });
  },
BrainLikeADullPencil
  • 11,313
  • 24
  • 78
  • 134

2 Answers2

4

You're missing the return statement:

  $scope.someFunc = function(){
    console.log("in someFunc");
    //  v----------------------------- here 
    return $http.get('http://localhost:8090/endpoint').success(function(data){
      console.log(data, "this logs");
    });
  },

Your attempt to call .then() is probably failing with a TypeError because the return value of $scope.someFunc() is undefined.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • `$q` shouldn't fail with a `TypeError`, it will just pass `undefined` to the following `then` callback. – Davin Tryon Jan 28 '15 at 15:32
  • @DavinTryon `undefined.then(...)` will fail with a `TypeError` because `undefine` doesn't have a `then` method. The error will not come from $q. – JLRishe Jan 28 '15 at 15:34
  • Ah, though you meant the `next` taking `undefined` as the callback param. Makes sense. – Davin Tryon Jan 28 '15 at 15:35
1

You need to return something for the next to run:

  return $http.get('http://localhost:8090/endpoint').success(function(data){
      console.log(data, "this logs");
  });
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132