node.js中的Redis异步/等待问题

时间:2018-05-13 04:27:14

标签: node.js redis async-await

方法asyncBlock正在正确执行。

但是(另外两种方法)当它被分成2个方法时,它的重新调整的承诺而不是实际值。

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 

输出

val Promise { <pending> }
val2 val1

1 个答案:

答案 0 :(得分:2)

异步函数返回一个promise,因此你在其中以同步方式处理事情,但你仍然以异步方式使用它。

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();