'async'/'await' in Node.js is not working in Node.js v8.1.0

Viewed 15174

I am trying to flush the Redis cache database and return the status in the response. But before the cache is cleared it returns the response.

In the below code the console.log() call will always print undefined since flushRedisDB is not awaited.

My Node.js version is v8.1.0

File myfile.js

async function flushRedisapi(request, response)
{
    try {
        var value = await redisModules.flushRedisDB();
        console.log("the value is: " + value);
        if(value)
            response.status(200).send({status : 'Redis Cache Cleared'});
        else
            response.status(400).send({status : "Redis Cache could not be flushed"});

    } catch (error) {
        response.status(400).send({status : "Redis Cache could not be flushed"});
    }
}

File redismodule.js

var redisClient;        // Global (avoids duplicate connections)

module.exports =
{
    openRedisConnection : function()
    {
        if (redisClient == null)
        {
            redisClient = require("redis").createClient(6379, 'localhost');
            redisClient.selected_db = 1;
        }
    },
    isRedisConnectionOpened : function()
    {
        if (redisClient && redisClient.connected == true)
        {
            return true;
        }
        else
        {
            if(redisClient)
                redisClient.end();  // End and open once more

            module.exports.openRedisConnection();

            return true;
        }
    },
    flushRedisDB: async function()
    {
        if(!module.exports.isRedisConnectionOpened())
            return false;

        await redisClient.flushall(function (err, result)
        {
            return (result == 'OK') ? true : false;
        });
    }
};

How can I solve this issue?

3 Answers
Related