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'
?
... 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.
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.
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.
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.
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).
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
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With