1

I want to make a function that supports done but without returning ajax.

function checkAndReturn(){
    if(global.id){
        return global.id; // the problem might be here 
    }else{
        return $.get("http://someurl.com",null,function(){...})
    }
}

Here checkAndReturn.done(function(){...}) works if global.id is not available, but it is not working if global.id is available.

I think I should be returning any other object and box my data to that object to make my done work, maybe xhr?.

Akshay
  • 3,558
  • 4
  • 43
  • 77
  • You need to know what you're expecting your method to return. In the second case (`$.get`) you're returning an xhr object. You need to either return the id in both cases, or cache the xhr object in a variable and return that the second time. – nbrooks Feb 26 '14 at 13:20
  • @nbrooks He cannot return the id in the second case, the call is asynchronous. – kapa Feb 26 '14 at 13:22

1 Answers1

3

You should return a (resolved) jQuery Deferred object. The jqXHR object returned by jQuery's AJAX functions is derived from Deferred as well, so the "interface" of your function will be clean - your function will return a Deferred in any case.

You could do something like this (just an example, adapt it to your use case):

function checkAndReturn(){
    if (global.id){
        return $.Deferred().resolve(global.id);
    }
    else {
        return $.get("http://someurl.com", null, function(){...})
    }
}

jsFiddle Demo

kapa
  • 77,694
  • 21
  • 158
  • 175