Node.js - Creating a Node.js Library that Supports Both Promises and Error-First Callbacks
Start
Example Module and Corresponding Program using Bluebird
math.js
'use strict';const Promise =require('bluebird');
module.exports ={// example of a callback-only methodcallbackSum:function(a, b, callback){if(typeof a !=='number')returncallback(newError('"a" must be a number'));if(typeof b !=='number')returncallback(newError('"b" must be a number'));returncallback(null, a + b);},// example of a promise-only methodpromiseSum:function(a, b){returnnewPromise(function(resolve, reject){if(typeof a !=='number')returnreject(newError('"a" must be a number'));if(typeof b !=='number')returnreject(newError('"b" must be a number'));resolve(a + b);});},// a method that can be used as a promise or with callbackssum:function(a, b, callback){returnnewPromise(function(resolve, reject){if(typeof a !=='number')returnreject(newError('"a" must be a number'));if(typeof b !=='number')returnreject(newError('"b" must be a number'));resolve(a + b);}).asCallback(callback);},};
index.js
'use strict';const math =require('./math');// classic callbacks
math.callbackSum(1,3,function(err, result){if(err)
console.log('Test 1: '+ err);else
console.log('Test 1: the answer is '+ result);});
math.callbackSum(1,'d',function(err, result){if(err)
console.log('Test 2: '+ err);else
console.log('Test 2: the answer is '+ result);});// promises
math.promiseSum(2,5).then(function(result){
console.log('Test 3: the answer is '+ result);}).catch(function(err){
console.log('Test 3: '+ err);});
math.promiseSum(1).then(function(result){
console.log('Test 4: the answer is '+ result);}).catch(function(err){
console.log('Test 4: '+ err);});// promise/callback method used like a promise
math.sum(8,2).then(function(result){
console.log('Test 5: the answer is '+ result);}).catch(function(err){
console.log('Test 5: '+ err);});// promise/callback method used with callbacks
math.sum(7,11,function(err, result){if(err)
console.log('Test 6: '+ err);else
console.log('Test 6: the answer is '+ result);});// promise/callback method used like a promise with async/await syntax(async()=>{try{let x =await math.sum(6,3);
console.log('Test 7a: '+ x);let y =await math.sum(4,'s');
console.log('Test 7b: '+ y);}catch(err){
console.log(err.message);}})();