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

时间:2015-01-20 23:47:48

标签: 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){
          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请求还是只是常规对象?

感谢您的帮助!

4 个答案:

答案 0 :(得分:3)

如果我理解正确,您的问题是t返回的对象是否是启用链接的承诺。您可以始终使用$q.when(obj)来包装对象,它将确保返回的对象始终是一个承诺并且可以链接。您需要确保以$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;
        })
}
  

when(value):将可能是值的对象或(第三方)包装成$ q保证。当您处理可能会或可能不是承诺的对象,或者承诺来自不可信任的来源时,这非常有用。

答案 1 :(得分:1)

您可以检查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
}

答案 2 :(得分:1)

修改后的代码

传递回调方法

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

答案 3 :(得分:0)

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

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