Reputation: 1103
For my projekt I'am using Node.js with express.js and redis.io as database. Now I have a get resource with query parameter. It should give me the IDs of libraries that hold a particular book. But I dont understand the processing order of my program. As you can see in the code below I print the libraries Array 3 times to the console.
var express = require('express');
var bodyParser = require('body-parser');
var redis = require('redis');
var db = redis.createClient();
var jsonParser = bodyParser.json();
var app = express();
app.use(jsonParser);
app.get('/test', function (req, res) {
if (req.query.book != null) {
var book_id = req.query.book;
var libraries = [];
db.get('book:' + book_id, function (err, rep) {
var book = JSON.parse(rep);
var libs = book.libraries;
libs.forEach(function (val) {
libraries.push(val.id);
});
console.log("1.: " + libraries);
});
console.log("2.: " + libraries);
}
console.log("3.: " + libraries);
});
app.listen(1337);
And this is the result in my console:
2.:
3.:
1.: 1,4
Can someone explain that? And why my array is emtpy on point 2 and 3?
Upvotes: 0
Views: 45
Reputation: 2371
Your callbacks are executed asynchronously. 2nd is log is first because it's in synchronous block before 3rd one. 1st shows up last, because it is called after you get result from database, which happens asynchronously, so after 2nd and 3rd parts of code.
Upvotes: 2