Reputation: 559
I have been watching some YouTube videos on Node.js and I am fascinated by the framework. A lot of folks put a fast food analogy around node where they say it is like taking an order; help the next customer; take an order; and so on with the callback being your order. Either I missed it or I just do not understand. But before a callback to occur does it have to read all the code?
Below is some code to test the flow so I get a better understanding, the results support that a callback will only occur after all the instructions have been completed. Meaning the contents of the file were not put to the console till after console out 15.
I just want to make sure I have this down right.
Putting it back in the terms of fast food, if three people were online to get coffee at the "Node Cafe" does customer 1 get their order before customer 3 places it?
Hope this makes sense!
var fs = require('fs');
function sql_file(sqlFilename, cb) {
var fileName = sqlFilename;
fs.readFile(fileName, function(err, buffer) {
if (err) return cb(err);
return cb(null, buffer.toString());
});
console.log('buffer');
}
module.exports.sql_file = sql_file;
console.log('1');
var misc = require('./foo.txt');
misc.sql_file('Account.sql', function(err, contents) {
console.log(contents);
});
console.log('2');
console.log('3');
console.log('4');
console.log('5');
console.log('6');
console.log('7');
console.log('8');
console.log('9');
console.log('10');
console.log('11');
console.log('12');
console.log('13');
console.log('14');
console.log('15');
Upvotes: 2
Views: 99
Reputation: 664513
does customer 1 get their order before customer 3 places it?
No. To put it in your fast food analogy:
There is only one waiter who deals with all customers (a single thread executing all actions). When there is a line (of statements) at the counter, he will need to process all of them at once. During that, he might issue (asynchronous) orders to other employees (background processes) as requested by the customer, but he must not wait for results and handle the next customer. When the queue is empty, he can get back to the orders, which might have been fulfilled by the cook in the meanwhile. He will wait until the cook notifies him that an order is finished, and then he can check the notes (closure of the callback) to see which customer ordered the food, then serve it. He will need to serve all dishes at once again, not being interrupted by other cooks.
For a technical explanation, read about the Node event loop.
Upvotes: 6