Skip to main content

Bluebird Promises Tutorial | Bluebird JS with NPM Example

What is Bluebird JS?

Bluebird JS is a fully-featured Promise library for JavaScript. The strongest feature of Bluebird is that it allows you to “promisify” other Node modules in order to use them asynchronously. Promisify is a concept applied to callback functions. This concept is used to ensure that every callback function which is called returns some value.

So if a NodeJS module contains a callback function which does not return a value, and if we Promisify the node module, all the function’s in that specific node module would automatically be modified to ensure that it returns a value.

So you can use BlueBird to make the MongoDB module run asynchronously. This just adds another level of ease when writing Node.js applications.

We will look at an example of how to use the bluebird module.

Our example will first establish a connection to the “Employee collection” in the “EmployeeDB” database. If “then” connection is established, then it will get all of the records in the collection and display them in the console accordingly.

How to Generate Promises with Bluebird JS Library

Here is the step by step example to generate promises with Bluebird JS library:

Step 1) Installing the NPM Modules

To use Bluebird from within a Node application, the Bluebird module is required. To install the Bluebird module, run the below command

npm install bluebird

Step 2) Include Bluebird modules

The next step is to include the bluebird module in your code and promisify the entire MongoDB module. By promisify, we mean that bluebird will ensure that each and every method defined in the MongoDB library returns a promise.

Bluebird JS Promises Example

Code Explanation:-

  1. The require command is used to include the Bluebird library.
  2. Use Bluebird’s .promisifyAll() method to create an async version of every method the MongoDB module provides. This ensures that each method of the MongoDB module will run in the background and ensure that a promise is returned for each method call in the MongoDB library.

Step 3) Connect to the Database

The final step is to connect to our database, retrieve all the records in our collection and display them in our console log.

Bluebird JS Promises Example

Code Explanation:-

  1. You will notice that we are using the “connectAsync” method instead of the normal connection method for connecting to the database. Bluebird actually adds the Async keyword to each method in the MongoDB library to distinguish those calls which return promises and those which don’t. So there is no guarantee that methods without the Async word will return a value.
  2. Similar to the connectAsync method, we are now using the findAsync method to return all of the records in the mongoDB ‘Employee’ collection.
  3. Finally, if the findAsync returns a successful promise we then define a block of code to iterate through each record in the collection and display them in the console log.

If the above steps are carried out properly, all of the documents in the Employee collection will be displayed in the console as shown in the output below.

Example of Bluebird JS Promises

Here is the code for your reference:

var Promise = require('bluebird');

var mongoClient = Promise.promisifyAll(require('mongodb')).MongoClient;

var url = 'mongodb://localhost/EmployeeDB';
mongoClient.connectAsync('mongodb://localhost/EmployeeDB')

.then(function(db) {
        return db.collection('Employee').findAsync({})

    })
    .then(function(cursor) {
        cursor.each(function(err, doc) {
            console.log(doc);
        })
    });

Comments

Popular posts from this blog

IOT Projects souce code

IOT  Projects souce code What is IoT? The Internet of Things (IoT) is a network where everyday objects like devices, vehicles, and appliances have sensors and internet connectivity. It lets them gather and share data, work together, and perform tasks without human control. This helps boost automation and efficiency across different areas. You can learn IoT to understand its core components and get further knowledge of its functionalities. 20 IoT Projects with Source Code When it comes to IoT, there are many interesting ideas to explore, from making your home smarter to making an autonomous drone. No matter if you’re just starting or have experience, here are 20 Internet of things projects for beginners and advanced professionals. Simple IoT Project Ideas for Beginners For beginner-level, you can start with simple and fun IoT project ideas that involve basic components like sensors, actuators, and microcontrollers. Below are a few of them: 1. Smart Home Automation Smart home automat...

Connecting R to MySql in English #Training Trains

software design institute training

  ONLINE-OFFLINE IN-PLANT/INTERNSHIP With Certificate Training For B.E(ECE,EEE,CSE,IT,AI,ML,DataScience,Cyper Security),MCA, B.Sc,M.E,M.Tech. @ TrainingTrains.Online Classes Available 100 % Job placement Training Full Stack Developer | Placement Training In-plant Training/Internship Training with Project supports the various Engineering and Non-Engineering, Arts Students to develop their Skills on the IT Companies/Corporate Expectations. DURATION OF IN-PLANT TRAINING: 1 week and Above.DURATION OF INTERNSHIP: 1 Month and Above Internship-inplant training For All Departments students, Internship- inplant Training Python | Java | Full Stack Development | UI & UX | C& C++ | Php | Web Designing - HTML, CSS, Java Script, Bootstrap | MEAN Stack | MERN Stack | MEARNStack | Android | Kotlin | Flutter | Database - Oracle, Mongo DB, MySQL, MS SQL Serer | Visual Studio Code | Objective C | Swift | Go Lang | Frame work - Laravel, Django, Vue JS | Machine Learning | React JS | ...