Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis Async / Await Issue in node.js

Method asyncBlock is getting executed properly.

but (other two methods) when its is split into 2 methods its retuning promise instead of the actual value.

https://runkit.com/sedhuait/5af7bc4eebb12c00128f718e

const asyncRedis = require("async-redis");
const myCache = asyncRedis.createClient();

myCache.on("error", function(err) {
    console.log("Error " + err);
});

const asyncBlock = async() => {
    await myCache.set("k1", "val1");
    const value = await myCache.get("k1");
    console.log("val2",value);

};
var setValue = async(key, value) => {
    await myCache.set(key, value);
};

var getValue = async(key) => {
    let val = await myCache.get(key);
    return val;
};
asyncBlock(); //  working 
setValue("aa", "bb"); // but this isn't 
console.log("val", getValue("aa"));//but this isn't 

Output

val Promise { <pending> }
val2 val1
like image 300
Sedhu Avatar asked May 13 '18 04:05

Sedhu


1 Answers

The async functions return a promise, so you are doing things in an sync style inside it but you still using it in async style.

var setValue = async(key, value) => {
  return await myCache.set(key, value);
};

var getValue = async(key) => {
  let val = await myCache.get(key);
  return val;
};

async function operations() {

  console.log(await setValue("aa", "bb"));
  console.log("val", await getValue("aa"));

}

operations();
like image 82
faressoft Avatar answered Oct 20 '22 09:10

faressoft