aka:JavaScript:Promises
- What is a promise?
- "In computer science, future, promise, and delay refer to constructs used for synchronizing in some concurrent programming languages. They describe an object that acts as a proxy for a result that is initially unknown, usually because the computation of its value is yet incomplete." http://en.wikipedia.org/wiki/Futures_and_promises
- Does JavaScript have promises?
- ES6 has.
- Some browsers have already implemented the ES6 promises.
- There is a polyfill for the ES6 promises.
- Node.js decided not to adopt promises as one of its core features on the early stages. That's why you see plenty of nested callbacks in the community.
- ES6 has.
- What is Q? I see this letter often when I read something about JavaScript promises.
- Q is a library that implements promises. There are some such libraries: Q, when, WinJS, and RSVP.js. All these libraries are Promise/A+ compliant. https://github.com/promises-aplus/promises-spec Please note that jQuery's q is not compliant to the standard.
- Can I use Q on node.js?
- Yes. 'npm install q' will do the work.
- But, most features of node.js are implemented in a CPS or callback style. So you have little benefit to use promises libraries like Q on node.js.
- No benefit?
- A benefit is a better code readability. You can avoid so-called callback hell, keeping your code look flat.
- Is that the only benefit?
- Ahm, actually, asynchronous code is just one of patterns you can use promises. One other example is lazy evaluations: you can postpone actual computation of something into the future when you need the value. I mean you don't use this kind of patterns in web programming.
- In web programming, communication with servers is a popular pattern to apply asynchronous way of writing such as promises. But in this case, promises are just a syntax sugar of underlying concurrent features such as multithreads or event emitter/loop systems host environments provide.
- Anyway, how can I create a promise object in node with Q?
- Here
var q = require('q'); function doSomethingAsync() { var deferred = q.defer(); setTimeout(function () { deferred.resolve('hello world'); }, 500); return deferred.promise; } doSomethingAsync().then(function (val) { console.log('Promise Resolved', val); });
- Here
- I don't like or understand promise examples that use timers like setTimeout. They look like sophistries.
- Chill out.
- What is this 'deferred'?
- Generally, a Deferred is an object that helps create and manipulate promises. A Deferred has a promise property that references the promise that it manages. It also has resolve and reject methods that are responsible for resolving / rejecting the promise.
- Really?
- Really. See the deferred object of the previous code:
{ promise: [object Object], resolve: [Function], fulfill: [Function], reject: [Function], notify: [Function] }
- Really. See the deferred object of the previous code: