Register Login Home / MonoX / Software Development / Blog / Support / About Us Knowledge is power. We love to share it. News related to Mono products, services and latest developments in our community. tihomir.kit Creating NodeJS modules with both promise and callback API support using Q 07/07/2014 - Categories: NodeJS If you're building your own NodeJS library and you like using promises, chances are you'll want to implement your module API through promises. However, you might also want to support the error-first callback pattern as well, for all the developers out there who prefer to use the standard NodeJS approach. Since Q is currently one of the most popular and well rounded JS promise libraries with NodeJS support, in this post we'll be using Q to implement a module function that will support dual promise/callback API's. // dual-module.js var Q = require('q'); module.exports = { getFullName: function (firstName, lastName, callback) { var deferred = Q.defer(); if (firstName && lastName) { var fullName = firstName + " " + lastName; deferred.resolve(fullName); } else { deferred.reject("First and last name must be passed."); } deferred.promise.nodeify(callback); return deferred.promise; } } The getFullName() function will always return a promise and if passed a callback (assuming it's a NodeJS-style callback), deferred.promise.nodeify() will register it. So, callback is an optional parameter. The getFullName() module function can now be used either through a promise... var DualModule = require('dual-module'); DualModule.getFullName("John", "Doe") .then(function (result) { // result returns "John Doe" }) .fail(function (error) { // error returns error message if either first or last name are null or undefined }); ... or through the standard NodeJS error-first callback: var DualModule = require('dual-module'); DualModule.getFullName("John", "Doe", function (error, result) { // error returns error message if either first or last name are null or undefined // result returns "John Doe" }); That's it, happy module writing! Tags: NodeJS callback error-first promises Q This content has not been rated yet. 1 2 3 4 5 Name:* E-mail:* Web site: Comment Notify me when new comments are added to this post SAVE COMMENT GENERAL / Click here to log in No account? Register here! Privacy policy Terms of use PRODUCTS & SERVICES / MonoX eCTD Office Web Application Optimizer Software development COMMUNITY / Blog Support forum Contact us SHOP / MonoX WAO Send us an e-mail SEND NOW Partners Follow us Copyright © 2003 - 2014 Mono Software Ltd.