且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-04 12:42:48

如果我正确地理解你的问题是由 T 返回的对象是一个承诺或不启用链。你可以做总是 $ q.when包装对象(OBJ) 它将确保对象返回始终是一个承诺,可以通过串连。您需要确保注入 $ Q 你正在做的方式 $ HTTP 。或只是包装测试值本身 VAR OBJ = $ q.when(值)回报的obj

  VAR T =功能(){
    VAR OBJ;
    VAR试验;
    // code,确定测试值
    如果(!测试){
       返回$ q.when(OBJ); //< - 收益$ q.when
    }
    返回getObj(URL)
        。然后(函数(OBJ){
            返回OBJ
        })
}VAR getObj =功能(){
    返回$ http.get(URL);
}VAR开放=功能(){
    //这将永远现在的工作对
    //返回T();应该足够,以及
    返回T()
        。然后(函数(OBJ){
            返回OBJ;
        })
}


  

当(值):包装一个对象可能是一个值或一个(第三方)当时能承诺到$ Q承诺。当你正在处理的对象可能会或可能不会是一个承诺,或者承诺来自于不可信任的来源,这是很有用的。


块引用>

I have a function that might return regular object or an 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 to check if returned object is through http request or just a regular object?

Thanks for the help!

If i understand correctly your issue is with the object returned by t is a promise or not to enable chaining. You could do always wrap the object with $q.when(obj) it will make sure object returned is always a promise and can be chained through. You need to make sure to inject $q the way you are doing $http. Or just wrap the test value itself 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 that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.