How can I return values ​​from anchored deferrals in jQuery?

I am trying to track 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 following is ajaxFetch() , a generic ajax handler that returns the expected pending ajax object. Let's say this is a string value: 'hello' . Server response a few 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 for the output of 'hello' ?

I think...

... that console.log() needs to be configured somehow as promise , but it is very difficult for me to understand jQuery documentation.

+6
source share
2 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 }); } 
+4
source

I'm not quite sure I understand what you're trying to do, but if you want to make callbacks using a deferred object in the context of the click handler, you can return the ajax function directly 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); }; 
+3
source

Source: https://habr.com/ru/post/949686/


All Articles