Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 638
tim Avatar asked Jul 17 '13 22:07

tim


People also ask

What is Deferred () used for?

Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.

How use jQuery Deferred and Promise?

promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists. If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point.

Can jQuery be Deferred?

The jQuery. Deferred method can be passed an optional function, which is called just before the method returns and is passed the new deferred object as both the this object and as the first argument to the function. The called function can attach callbacks using deferred. then() , for example.

How do I use Javascript Deferred?

The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing. Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).


1 Answers

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
   });
}
like image 164
A. Wolff Avatar answered Jan 02 '23 07:01

A. Wolff