Mario Levrero
Mario Levrero

Reputation: 3367

Return JQuery.When deferred resolved

I have a function that include a function to an async function, but I need to return the first one when the async call has been resolved. I'm trying using

return JQuery.when()     

The following function is a resume.

function getData(x){
 if (x = 1){
    return JQuery.when(asynFunction().then(function (data){
        (...);
        return;
    });
 }
 else {
  (...)
  return;
 }

}

The objective is that getData() doesn't return until the async call has finished. Any idea?

Thanks for your time!

Upvotes: 0

Views: 121

Answers (1)

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

Assuming that asynFunction() returns a Promise, getData might, at its simplest, look like this :

function getData(x) {
    if (x = 1) {
        return asynFunction();
    }
    else {
        var myValue = 'whatever';
        return myValue;
    }
}

However it's often better (though not absolutely necessary) to arrange for a function to return a Promise in all circumstances. This guarantees that wherever getData() is called, the result can be handled in an asynchronous manner (ultimately with .then or .done()) even if it is synchronously derived.

function getData(x) {
    if (x = 1) {
        return asynFunction();
    }
    else {
        ...
        var myValue = 'whatever';
        return jQuery.when(myValue);
    }
}

Upvotes: 1

Related Questions