logo

The next-generation blog, news, and article for you to start sharing your stories today!

Cassandra Async Await Query In Node JS

How to write async await query in cassandra with NodeJs ?

Well, Cassandra is open source hight performance nosql database system developed by Apache.

Here is link https://cassandra.apache.org

Its Manage massive amounts of data, fast, without losing sleep.

 

Connect Cassandra Database Using Nodejs

Here is cassandra - nodejs driver availabe to connect your cassandra database using nodeJs.

See the following script to install cassandra node driver to nodejs application

$ npm install cassandra-driver

 

Basic Cassandra Query Example

const cassandra = require('cassandra-driver');

const client = new cassandra.Client({
  contactPoints: ['h1', 'h2'],
  localDataCenter: 'datacenter1',
  keyspace: 'ks1'
});

const query = 'SELECT name, email FROM users WHERE key = ?';

client.execute(query, [ 'someone' ])
  .then(result => console.log('User with email %s', result.rows[0].email));

 

Write Async Await Cassandra Query

Method 1.

 function getData() {
        return new Promise(async function (resolve, reject) {
            try {
                const query = 'SELECT name, email FROM users WHERE key = ?';
                client.execute(query, [ 'someone' ])
                .then(result => resolve(result));
            } catch (error) {
                console.log(error);
                error.code = 500;
                reject(error);
            }
        })
    }

Accessing the function like


async function getMyData() {

   let result = await getData()

}

 

Method 2

async function getData() {
            try {
                const query = 'SELECT name, email FROM users WHERE key = 1';
                result = await client.execute(query)
                return result // Or you can process your result
            } catch (error) {
                console.log(error);
                error.code = 500;
                throw (error);
            }
        })
    }

 

 

Conclusion

Hello I am Vikram Parihar, So we have learnt how to write async and await query in cassandra nodejs. Feel free to write comment and feedback.

avatar

Vikram Parihar

An editor at Keyscript

Vikram Parihar is an senior software engineer. He is working since 2013 in web development technologies. He works in NodeJS, Angular, Vue, PHP, Laravel, Express JS and various popular technologies.