1

I am new to promises but I am trying to get a function (which returns a number) to execute before continuing on. I have tried the following and none work:

var whatNumber = function(){
 var defer = $q.defer();
 myNumber.get().then(defer.resolve);
 return defer.promise;
}

I also tried:

var whatNumber = function(){
 var defer = $q.defer();
 defer.resolve( myNumber.get());
 return defer.promise;
}

And finally I tried it without promises:

var whatNumber = function(){
 myNumber.get().then(function(result) {
   return result;
 });
}

Anyone have any ideas what I am doing wrong?

lk1234
  • 113
  • 1
  • 1
  • 6
  • 1
    You've shown us the function itself, not show us how you're using it, and describe what doesn't work exactly (Expected vs. Actual result) – Alon Eitan May 04 '16 at 20:03
  • myNumber.get() is working fine, returns a number. The first one hits the function and runs through but the code stops - it never hits defer.resolve or the promise The second one doesnt wait for myNumber.get() to execute before hitting the promise The third one never hits return result... just runs through the function and stops – lk1234 May 04 '16 at 20:12
  • I think the problem might be in the implementation of `myNumber.get()`. Can you show us, what is going on there? What is logged by `console.log(myNumber.get())`? – Thomas May 04 '16 at 22:09

2 Answers2

3

You should read about deffered antipattern In your case you can just return myNumber.get(); from the function:

var whatNumber = function(){
 return myNumber.get();
}

Or, if you need to return specific property from the result:

var whatNumber = function(){
 return myNumber.get().then(function(result) {
   return result.data;
 });
}

If you want to use the antipattern method (which you should avoid), then you need to resolve the promise and pass the parameters:

var whatNumber = function(){
 var defer = $q.defer();
 myNumber.get().then(function(result) {
   defer.resolve(result);
 });
 return defer.promise;
}

whatNumber().then(function(result) {
  console.log(result);
});
Community
  • 1
  • 1
Alon Eitan
  • 11,997
  • 8
  • 49
  • 58
2

You are close, you just have your resolve aimed incorrectly from what I can see. You need to resolve the value you plan on using (the data)

var whatNumber = function(){
 var defer = $q.defer();
 myNumber.get().then(function(response){
    defer.resolve(response.data)
 });
 return defer.promise;
}
AlphaG33k
  • 1,588
  • 1
  • 12
  • 24