Wednesday, 20 July 2016

What are the differences between Deferred, Promise and Future in JavaScript?



What are the differences between Deferreds, Promises and Futures?
Is there a generally approved theory behind all these three?


Answer




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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...