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?
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);
});
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.