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...");
                }
            });
        }
    });    
}
Sharath
  • 2,348
  • 8
  • 45
  • 81
  • 2
    You can use promises to make your code cleaner [read more](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise) ... there are also several promise modules for node ... just search for it in NPM like https://www.npmjs.com/package/promise-call – rafaelcastrocouto Nov 20 '15 at 12:41
  • thanks for the response Rafael, I tried understanding promises but not sure about it. If you don't mind can you convert the above code using promises so that I get a clear picture of understanding. – Sharath Nov 20 '15 at 12:45
  • @Sharath http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises/ and http://bluebirdjs.com/docs/api/promise.promisifyall.html – Benjamin Gruenbaum Nov 20 '15 at 12:48

2 Answers2

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.

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
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 
})
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504