tim
tim

Reputation: 3903

how can I return values from chained deferreds in jQuery?

I'm trying to trace the return value from a function call:

$('#button').on('click', function(){
   console.log( getMessage(3) ); // I'm trying to get this to "hang" until ajax-related stuff is finished below
});

The ajaxFetch() below is a generic ajax handler that returns the expected ajax deferred object. let's assume it's a string value: 'hello'. Server response is several seconds.

function getMessage(id){
   ajaxFetch(id).done(function(result){
      // ... more stuff happening, but not relevant
   }).then(function(result){
      return (result); // I thought this would return to the click handler
   });
}

How can I get my trace to output 'hello'?

I think...

... that the console.log() needs to be somehow set up as a promise but I'm having a really hard time understanding the jQuery documentation.

Upvotes: 9

Views: 14251

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

Return the promise interface and code logic from it:

 $('#button').on('click', function(){
        $.when(getMessage(3)).then(function(result){console.log(result)});
    });

function getMessage(id){
   return ajaxFetch(id).done(function(result){
      // ... more stuff happening, but not relevant
   }).then(function(result){
      return result; //needed, otherwise it will return the object, not the result
   });
}

Upvotes: 5

mcbex
mcbex

Reputation: 444

I'm not completely sure I understand what you're trying to do, but if you want to execute callbacks using the deferred object within the context of the click handler you can return the ajax function itself from getMessage. Try something like this: (untested)

$('#button').on('click', function(){
    getMessage(3).then(function(result) {
        // do success callback here
        console.log(result); // 'hello'
    }, function(result) {
        // do fail callback here
    });
});

function getMessage(id){
    return ajaxFetch(id);
};

Upvotes: 3

Related Questions