Getting started with Node.jsnpmWeb Apps With ExpressFilesystem I/OExporting and Consuming ModulesExporting and Importing Module in node.jsInstalling Node.jsMySQL integrationReadlinepackage.jsonEvent EmittersAutoreload on changesEnvironmentCallback to PromiseExecuting files or commands with Child ProcessesCluster ModuleException handlingKeep a node application constantly runningUninstalling Node.jsnvm - Node Version ManagerhttpUsing StreamsDeploying Node.js applications in productionSecuring Node.js applicationsMongoose Libraryasync.jsFile uploadSocket.io communicationMongodb integrationHandling POST request in Node.jsSimple REST based CRUD APITemplate frameworksNode.js Architecture & Inner WorkingsDebugging Node.js applicationNode server without frameworkNode.JS with ES6Interacting with ConsoleCassandra IntegrationCreating API's with Node.jsGraceful ShutdownUsing IISNode to host Node.js Web Apps in IISCLINodeJS FrameworksgruntUsing WebSocket's with Node.JSmetalsmithParsing command line argumentsClient-server communicationNode.js Design FundamentalConnect to MongodbPerformance challengesSend Web NotificationRemote Debugging in Node.JSMysql Connection PoolDatabase (MongoDB with Mongoose)Good coding styleRestful API Design: Best PracticesDeliver HTML or any other sort of fileTCP SocketsHackBluebird PromisesAsync/AwaitKoa Framework v2Unit testing frameworksECMAScript 2015 (ES6) with Node.jsRouting ajax requests with Express.JSSending a file stream to clientNodeJS with RedisUsing Browserfiy to resolve 'required' error with browsersNode.JS and MongoDB.Passport integrationDependency InjectionNodeJS Beginner GuideUse Cases of Node.jsSequelize.jsPostgreSQL integrationHow modules are loadedNode.js with OracleSynchronous vs Asynchronous programming in nodejsNode.js Error ManagementNode.js v6 New Features and ImprovementEventloopNodejs Historypassport.jsAsynchronous programmingNode.js code for STDIN and STDOUT without using any libraryMongoDB Integration for Node.js/Express.jsLodashcsv parser in node jsLoopback - REST Based connectorRunning node.js as a serviceNode.js with CORSGetting started with Nodes profilingNode.js PerformanceYarn Package ManagerOAuth 2.0Node JS LocalizationDeploying Node.js application without downtime.Node.js (express.js) with angular.js Sample codeNodeJs RoutingCreating a Node.js Library that Supports Both Promises and Error-First CallbacksMSSQL IntergrationProject StructureAvoid callback hellArduino communication with nodeJsN-APIMultithreadingWindows authentication under node.jsRequire()Route-Controller-Service structure for ExpressJSPush notifications

Callback to Promise

Other topics

Promisifying a callback

Callback-based:

db.notification.email.find({subject: 'promisify callback'}, (error, result) => {
   if (error) {
       console.log(error);
   }

   // normal code here
});

This uses bluebird's promisifyAll method to promisify what is conventionally callback-based code like above. bluebird will make a promise version of all the methods in the object, those promise-based methods names has Async appended to them:

let email = bluebird.promisifyAll(db.notification.email);

email.findAsync({subject: 'promisify callback'}).then(result => {

    // normal code here
})
.catch(console.error);

If only specific methods need to be promisified, just use its promisify:

let find = bluebird.promisify(db.notification.email.find);

find({locationId: 168}).then(result => {
    
    // normal code here
});
.catch(console.error);

There are some libraries (e.g., MassiveJS) that can't be promisified if the immediate object of the method is not passed on second parameter. In that case, just pass the immediate object of the method that need to be promisified on second parameter and enclosed it in context property.

let find = bluebird.promisify(db.notification.email.find, { context: db.notification.email });

find({locationId: 168}).then(result => {

    // normal code here
});
.catch(console.error);

Manually promisifying a callback

Sometimes it might be necessary to manually promisify a callback function. This could be for a case where the callback does not follow the standard error-first format or if additional logic is needed to promisify:

Example with fs.exists(path, callback):

var fs = require('fs');

var existsAsync = function(path) {
  return new Promise(function(resolve, reject) {
    fs.exists(path, function(exists) {
      // exists is a boolean
      if (exists) {
        // Resolve successfully
        resolve();
      } else {
        // Reject with error
        reject(new Error('path does not exist'));
      }
    });
});

// Use as a promise now
existsAsync('/path/to/some/file').then(function() {
  console.log('file exists!');
}).catch(function(err) {
  // file does not exist
  console.error(err);
});

setTimeout promisified

function wait(ms) {
    return new Promise(function (resolve, reject) {
        setTimeout(resolve, ms)
    })
}

Contributors

Topic Id: 2346

Example Ids: 7711,9531,20131

This site is not affiliated with any of the contributors.