Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  35] [ 2]  / answers: 1 / hits: 113509  / 13 Years ago, sat, july 23, 2011, 12:00:00

What are the differences between Deferreds, Promises and Futures?

Is there a generally approved theory behind all these three?


More From » promise

 Answers
2

In light of apparent dislike for how I've attempted to answer the OP's question. The literal answer is, a promise is something shared w/ other objects, while a deferred should be kept private. Primarily, a deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.



If you're interested in the minutiae, then examine Promises/A+.






So far as I'm aware, the overarching purpose is to improve clarity and loosen coupling through a standardized interface. See suggested reading from @jfriend00:




Rather than directly passing callbacks to functions, something which
can lead to tightly coupled interfaces, using promises allows one to
separate concerns for code that is synchronous or asynchronous.




Personally, I've found deferred especially useful when dealing with e.g. templates that are populated by asynchronous requests, loading scripts that have networks of dependencies, and providing user feedback to form data in a non-blocking manner.



Indeed, compare the pure callback form of doing something after loading CodeMirror in JS mode asynchronously (apologies, I've not used jQuery in a while):



/* assume getScript has signature like: function (path, callback, context) 
and listens to onload && onreadystatechange */
$(function () {
getScript('path/to/CodeMirror', getJSMode);

// onreadystate is not reliable for callback args.
function getJSMode() {
getScript('path/to/CodeMirror/mode/javascript/javascript.js',
ourAwesomeScript);
};

function ourAwesomeScript() {
console.log(CodeMirror is awesome, but I'm too impatient.);
};
});


To the promises formulated version (again, apologies, I'm not up to date on jQuery):



/* Assume getScript returns a promise object */
$(function () {
$.when(
getScript('path/to/CodeMirror'),
getScript('path/to/CodeMirror/mode/javascript/javascript.js')
).then(function () {
console.log(CodeMirror is awesome, but I'm too impatient.);
});
});


Apologies for the semi-pseudo code, but I hope it makes the core idea somewhat clear. Basically, by returning a standardized promise, you can pass the promise around, thus allowing for more clear grouping.


[#91039] Friday, July 22, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaycoborionc

Total Points: 220
Total Questions: 106
Total Answers: 120

Location: Kenya
Member since Mon, Jun 14, 2021
3 Years ago
;