Making promise-based actions

Starting off with Q, perform actions that return promises. Let's say, make Node.js action http.get as the promised action:

// using-promise.js
var httpGet = function (opts) {
     var deferred = Q.defer();
     http.get(opts, deferred.resolve);
     return deferred.promise;
};

Later, you can use: httpGet(...).then(function (res) {...}); but you have to make sure that functions return promises. The first Q.defer() returns a set of an empty promise and operations for it. The deferred.promise is the empty promise which fixes a certain value:

// promise-resolve-then-flow.js
var deferred = Q.defer();
deferred.promise.then(function (obj) {
    console.log(obj);
});

deferred.resolve("Hello World");

This prints Hello World to the console. In general, ...

Get Mastering JavaScript Promises now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.