【发布时间】:2019-04-16 18:26:45
【问题描述】:
我试图深入了解 Stephen Grinder 的高级 NodeJS 概念。
Stephen 试图教授 redis 的基础知识,他做了这样的事情
app.get('/api/blogs', requireLogin, async (req, res) => {
//This time we are setting
const redis = require('redis')
const redisURL = 'redis://127.0.0.1:6379';
const client = redis.createClient(redisURL);
const util = require('util')
client.get = util.promisify(client.get)
//We are checking if we have ever fetched any blogs related to the user with req.user.id
const cachedBlog = await client.get(req.user.id)
//if we have stored list of blogs, we will return those
if (cachedBlog) {
console.log(cachedBlog)
console.log("Serving from Cache")
return res.send(JSON.parse(cachedBlogs))
} //this is JSONIFIED as well so we need to convert it into list of arrays
console.log("serving from Mongoose")
//if no cache exsist
const blogs = await Blog.find({_user: req.user.id})
//blogs here is an object so we would need to stringfy it
res.send(blogs);
client.set(req.user.id, JSON.stringify(blogs))
})
如果我们更改顺序,它可以正常工作,但在最后两行中
client.set(req.user.id, JSON.stringify(blogs))
res.send(blogs);
它不显示我的博客。
由于在 API 内部,我正在考虑将它们都异步运行,我认为顺序无关紧要。
谁能告诉我我错过了什么或无法理解什么?
【问题讨论】:
-
所以也不例外?
-
显示是什么意思?从 res.send 还是在下一次调用 console.log 中?
-
@Tzomas 来自 res.send
标签: node.js asynchronous redis