3

I have a requirement where I need to get the records from table 1 and store in redis cache and once redis cache is finished storing, get table 2 records and store in redis cache. So there are 4 asynchronous functions.

Steps:

  1. Get table 1 records
  2. Store in redis cache
  3. Get table 2 records
  4. Store in redis cache

What is the correct procedure to handle it.

Below is the code which I have written to handle it. Please confirm whether its the right procedure or any other ways to handle it as per node.js

var redis = require("redis");
var client = redis.createClient(6379, 'path', {
    auth_pass: 'key'
});

var mysqlConnection = // get the connection from MySQL database

get_Sections1()

function get_Sections1() {
    var sql = "select *from employee";

    mysqlConnection.query(sql, function (error, results) {
        if (error) {
            console.log("Error while Sections 1 : " + error);
        } else {
            client.set("settings1", JSON.stringify(summaryResult), function (err, reply){
                if (err) {
                    console.log("Error during Update of Election : " + err);
                } else {
                    get_Sections2();
                }
            });
        }
    });
}

function get_Sections2() 
{
    var sql = "select *from student";            

    mysqlConnection.query(sql, function (error, results) 
    {
        if (error) 
        {
            console.log("Error while Sections 2 : " + error);
        }
        else 
        {
            client.set("settings2", JSON.stringify(summaryResult), function (err, reply) 
            {
                if (err) 
                {
                    console.log("Error during Update of Election : " + err);
                }
                else 
                {
                    console.log("Finished the task...");
                }
            });
        }
    });    
}
3

2 Answers 2

2

Create two parameterised functions. One for retrieval, one for storing.

Then promisify them both.

Then write:

return getTableRecords(1)
  .then(storeInRedisCache)
  .then(getTableRecords.bind(null,2))
  .then(storeInRedisCache)
  .then(done);

To promisify a function, something like this might work:

var getEmployees = new Promise(function(resolve, reject) {
  var sql = "select *from employee";

  mysqlConnection.query(sql, function (error, results) {
    if (error) {
      return reject();
    } else {
      return resolve(results);
    }
  });
});

If you are using an old version of NodeJS you will need a polyfill for Promise.

Sign up to request clarification or add additional context in comments.

1 Comment

should I install promise npm module for this concept
2

Here is an alternative to Ben Aston's solution using Promise.coroutine assuming promises:

const doStuff = Promise.coroutine(function*(){
     const records = yield getTableRecords(1);
     yield storeRecordsInCache(records);
     const otherRecords = yield getTableRecords(2);
     yield storeRecordsInCache(otherRecords); // you can use loops here too, and try/cath 
});

doStuff(); // do all the above, assumes promisification

Alternatively, if you want to use syntax not yet supposed in Node (and use Babel to get support) you can do:

async function doStuff(){
     const records = await getTableRecords(1);
     await storeRecordsInCache(records);
     const otherRecords = await getTableRecords(2);
     await storeRecordsInCache(otherRecords); // you can use loops here too, and try/cath 
})

4 Comments

Promise.coroutine is part of which ES specification?
@BenAston none, it's a shim for async functions based on generators. I though you knew that much :) It uses bluebirdjs.com/docs/api/promise.coroutine.html but you can use co or a number of other libraries providing different solutions.
@BenjaminGruenbaum Is it similar to async and await concept in c#
Yes, it is very similar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.