Node-js
How to Download & Install Node.js and NPM on Window
To start building your Node.js applications, the first step is the installation of the node.js...
Bluebird 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 Node JS 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.
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) 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.
Code Explanation:-
Step 3) The final step is to connect to our database, retrieve all the records in our collection and display them in our console log.
Code Explanation:-
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.
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);
})
});
To start building your Node.js applications, the first step is the installation of the node.js...
The Node.js framework is mostly used to create server-based applications. The framework can easily be...
What is GraphQL? GraphQL is an application layer server-side technology which is developed by...
What is Node JS? Node.js is a cross-platform runtime library and environment for running...
In this tutorial, we are going to learn about Generators and their differences with Callbacks What...
What is GraphQL? GraphQL is an application layer server-side technology which is developed by...