Book Image

Mastering JavaScript Promises

Book Image

Mastering JavaScript Promises

Overview of this book

Table of Contents (16 chapters)
Mastering JavaScript Promises
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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, you can transform usual callback actions:

// promise-translate-action.js
action(arg1, arg2, function (result) {
    doSomething(result);
});

To promise actions:

// promise-translate-action.js
var promiseAction = function (arg1...