Javascript 在我的情况下如何返回对象?

Javascript 在我的情况下如何返回对象?,javascript,angularjs,Javascript,Angularjs,我有一个函数,可以返回常规对象或http请求对象 我有点像 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){

我有一个函数,可以返回常规对象或http请求对象

我有点像

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();
如何检查返回的对象是通过http请求还是仅仅是一个普通对象


谢谢你的帮助

您可以检查t的类型是函数还是对象。为了调用它,必须将其作为函数键入

//this won't work for regular object, it has to be http object
if( typeof t !== "function" ){
 //return; or handle case where t is a plain object
}

您可以验证返回对象是否具有承诺对象:

var open = function() {
    var result = t();
    //Verify whether the return object has a promise object or not
    if(angular.isObject(result.promise)
    return result
        .then(function(obj) {
            return obj;
        })
}
修改代码

传递回调方法

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();

如果我理解正确,您的问题在于
t返回的对象是否承诺启用链接。您可以始终使用它来包装对象,以确保返回的对象始终是一个承诺,并且可以链接。您需要确保注入
$q
的方式与执行
$http
的方式相同。或者用
var obj=$q.when(value)
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;
        })
}
var t=function(){
var-obj;
var检验;
//确定测试值的代码
如果(!测试){

return$q.when(obj);//调用普通对象会得到
未捕获的类型错误:对象不是函数
。我猜他说的是承诺对象和非承诺对象。如果是非承诺对象
t()。然后()
调用将失败。@PSL-是的,我不确定
打开的意图也是什么。因为对象仅从那里传递,而且它最初设置为
{}
在本例中,再次传递
t
可能是有意义的,这就是为什么我试图在回答中指出
//return;
。另一方面,我也喜欢您将对象包装在承诺中的想法,在本例中,这可能是最佳实践。传递回调的问题是您失去了优势承诺和承诺链。