方法 asyncBlock 正在正确执行。
但是(其他两种方法)当它被分成 2 种方法时,它的重新调整 promise 而不是实际值。
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
最佳答案
异步函数返回一个 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();
关于node.js - node.js 中的 Redis 异步/等待问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50312759/