How do I return an object in my case?
I have a function that can return a normal or http request object.
I have something like
var t = function() {
var obj
var test;
//code to determine test value
//return object depends on test value,
//if test is undefined, return regular obj,
//if not make a http request.
if (!test){
return obj;
}
return getObj(url)
.then(function(obj){
return obj
})
}
var getObj = function() {
return $http.get(url);
}
var open = function() {
//this won't work for regular object, it has to be http object
return t()
.then(function(obj) {
return obj;
})
}
var obj = open();
How can I check if an object is returned via an HTTP request or a regular object?
Thanks for the help!
source to share
If I understand correctly your problem with the object being returned t
is a promise or not to chain. You can always wrap the object $q.when(obj)
to ensure that the returned object is always a promise and can be bound. You must be sure to enter the $q
way you are doing $http
. Or just circle the test value with var obj = $q.when(value)
and return obj
.
var t = function() {
var obj;
var test;
//code to determine test value
if (!test){
return $q.when(obj); //<-- return $q.when
}
return getObj(url)
.then(function(obj){
return obj
})
}
var getObj = function() {
return $http.get(url);
}
var open = function() {
//this will always work now on
//return t(); should be enough as well
return t()
.then(function(obj) {
return obj;
})
}
when (value): Wraps an object, which can be a value or (third party), and then can promise in a promise in $ q. This is useful when you are dealing with an object that may or may not be a promise, or if the promise comes from a source that cannot be trusted.
source to share
Modified code
Skip callback method
var t = function(cb) {
var obj
var test;
//code to determine test value
//return object depends on test value,
//if test is undefined, return regular obj,
//if not make a http request.
if (!test){
cb(obj);
}
return getObj(url)
.then(function(obj){
cb(obj)
})
}
var getObj = function() {
return $http.get(url);
}
var open = function() {
//this won't work for regular object, it has to be http object
return t(function(obj) {
// write code dependent on obj
})
}
var obj = open();
source to share