psorensen
psorensen

Reputation: 827

jQuery return value of deferred.then success when in function

I've written a function that I want to return the results of a successful deferred function. However, since the value I want returned is in the scope of the doneCallbacks, the runSearch() function returns undefined when running console.log(runSearch()). How can I have the containing function return the returned value of a successful deferred.then() ?

function runSearch(){   
    $.get( "search.php" ).then(
      function() {
        // I want runSearch() to return the results of this function 
      }, function() {
        console.log( "$.get failed!" );
      }
    );
}

EDIT: Thanks for all the help everyone. Since my goal was to user the return value in a function, I just included the function in the doneCallbacks.

function runSearch(){   
    $.get( "search.php" ).then(
      function() {
        var returnValue = 'Return Value'
        function doSomethingWithReturn(returnValue) {
            console.log(returnValue);
        }
        doSomethingWithReturn(returnValue);
      }, function() {
        console.log( "$.get failed!" );
      }
    );
}
runSearch(); // successfully logs returnValue to console.

May not be the most elegant solution, but works for this situation.

Upvotes: 0

Views: 1070

Answers (1)

SLaks
SLaks

Reputation: 887415

You can't do that.

Instead, you need to return the promise, then make all code that calls that function asynchronous, as well.

For more information see my blog.

Upvotes: 1

Related Questions