我必须使用亚马逊的 aws 管理 json 的转换,并将缓存保存在 redis 中。
async function translateSomething(trans, p1, sourceLan, targetLan) {
var paramsName = {
Text: p1,
SourceLanguageCode: sourceLan,
TargetLanguageCode: targetLan,
};
let myPromise = () =>
new Promise((resolve, reject) => {
trans.translateText(paramsName, function (err, data) {
if (err) throw err;
if (data) {
console.log("translated", data.TranslatedText);
resolve(data.TranslatedText);
}
});
});
let res = await myPromise();
return res;
}
// and this function to check if the value is in the menu or not
function storeOrFound(p1, value, sourceLan, targetLan) {
return redisClient.get(p1, async (err, result) => {
if (err) console.log("err", err);
if (result) {
console.log("element is already in cache", JSON.parse(result).val);
let tmp = JSON.parse(result).val;
return tmp;
} else {
var translate = new AWS.Translate({ region: AWS.config.region });
let val = await translateSomething(
translate,
value,
sourceLan,
targetLan,
);
redisClient.setex(
p1,
3600,
JSON.stringify({ source: "Redis Cache", val }),
);
return val;
}
});
}
// and after i execute the query of the db i use this function to check if is present or not on the db or not
something().then((doc) => {
for (let i = 0; i < doc.items.length; i++) {
const menuRedisKeyName = `name:${doc.items[i].name}21`;
doc.items[i].name = storeOrFound(
menuRedisKeyName,
doc.items[i].name,
menuLang,
targetLan,
);
}
console.log("JSON", JSON.stringify(doc));
res.end(JSON.stringify(doc));
});
问题是方法 storeOrFound 返回 true 或 false (因为 return redisClient.get 返回 true 或 false 对象是否存在。管理这个问题的任何想法?也在控制台上我看到 console.log(" 元素已经在缓存中”..) 打印在最后。我错过了同步的东西吗?