'use strict'; let debug = require('debug'); module.exports = { promisedNaturalAdd: promisedNaturalAdd, cbToPromise: cbToPromise }; // NOTE: functions passed to `then` are named with the aim to make it // clearer for some part audience // Remember what a promise is, returning one from a custom function function promisedNaturalAdd(num1, num2) { let d = debug('helpers:promisedNaturalAdd'); d('Delayed Natural Add: START'); let p = new Promise(function (resolve, reject) { // This executes synchronous d('Executing promise callback'); if ((num1 < 0) || (num2 < 0)) { reject(new Error('arguments must be natural numbers')); return; } resolve(num1 + num2); }).then( // This two functions are called asynchronous. // It does NOT matter if the functions passed to // the Promise constructor are called synchronously or asynchronously function resolve(res) { d('This only forward the result'); return res; }, function reject(err) { d('This only forward the error'); throw err; } ); d('Delayed Natural Add: END'); return p; } function cbToPromise(fn) { let params = Array.prototype.slice.call(arguments, 1); return new Promise((resolve, reject) => { params.push(function (err) { if (err) { reject(err); return; } switch (arguments.length) { case 1: resolve(); break; case 2: resolve(arguments[1]); break; default: resolve(Array.prototype.slice.call(arguments, 1)); } }); fn.apply(null, params); }); }