I have my app.js, which has the following endpoint. This endpoint obviously acts weird, because it expects data to return before it says res.send(data), which is the wrong way to do Node.js.
I am not sure how to modify my code, so I get the data from users.GetUsers, and can send it to the client with res.send(data).
App.js code:
var http = require('http');
var express = require('express');
var users = require('./users');
client = redis.createClient();
var app = express();
var port = 4000;
app.listen(port);
app.get('/users',function(req,res) {
var data = users.getUsers(req,res);
console.log('data: ' + data);
res.send(data);
});
My users module:
var mongoose = require('mongoose');
var redis = require('redis');
client = redis.createClient();
exports.getUsers = function(req,res) {
var cacheKey = 'userKey';
//client.del(cacheKey);
client.get(cacheKey,function(err,data) {
if(err || data === null) {
mongoose.model('users').find(function(err,users) {
console.log('Setting cache: ' + cacheKey);
client.set(cacheKey,users,redis.print);
return users;
});
} else {
console.log('Find data in cache');
return data;
}
});
};
My problem:
My variable data in App.js, will always be undefined. How do I modify my call, so I can get the data to the server when it is ready?
Returning a value from a callback is meaningless because the return value is almost always ignored. Instead what is typically done is a callback is passed to the asynchronous function. Then inside your function, you execute the callback with an error as the first argument (null/undefined if no error) and then your results as the second or more arguments.
Example:
app.js:
app.get('/users', function(req, res) {
users.getUsers(req, res, function(err, data) {
console.log('data: ' + data);
res.send(data);
});
});
users.js:
exports.getUsers = function(req, res, cb) {
var cacheKey = 'userKey';
//client.del(cacheKey);
client.get(cacheKey,function(err, data) {
if (err || data === null) {
mongoose.model('users').find(function(err, users) {
console.log('Setting cache: ' + cacheKey);
client.set(cacheKey, users, redis.print);
cb(err, users);
});
} else {
console.log('Find data in cache');
cb(null, data);
}
});
};