6

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
1
  • All async functions return a promise - that's how they work. The resolved value of that promise (which you can get with .then() or await) on the promise will be the value you returned from the async function. Commented May 13, 2018 at 4:57

1 Answer 1

8

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();
Sign up to request clarification or add additional context in comments.

Comments

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.