Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node.js design patterns unleashing zalgo why is the asynchronous path consistent?

In the great book i'm reading now NodeJs design patterns I see the following example:

var fs = require('fs');
var cache = {};

function inconsistentRead(filename, callback) {
    if (cache[filename]) {
        //invoked synchronously
        callback(cache[filename]);
    } else {
        //asynchronous function
        fs.readFile(filename, 'utf8', function(err, data) {
            cache[filename] = data;
            callback(data);
        });
    }
}

then:

function createFileReader(filename) {
    var listeners = [];
    inconsistentRead(filename, function(value) {
        listeners.forEach(function(listener) {
            listener(value);
        });
    });
    return {
        onDataReady: function(listener) {
            listeners.push(listener);
        }
    };
}

and usage of it:

var reader1 = createFileReader('data.txt');
reader1.onDataReady(function(data) {
console.log('First call data: ' + data);

The author says that if the item is in cache the behaviour is synchronous and asynchronous if its not in cache. I'm ok with that. he then continues to say that we should be either sync or async. I'm ok with that.

What I don't understand is that if I take the asynchronous path then when this line var reader1 = createFileReader('data.txt'); is executed can't the asynchronous file read finish already and thus the listener won't be registered in the following line which tries to register it?

like image 892
Jas Avatar asked Apr 22 '16 13:04

Jas


People also ask

Is node js always asynchronous?

js is an asynchronous event-driven JavaScript runtime and is the most effective when building scalable network applications. Node. js is free of locks, so there's no chance to dead-lock any process.

Which of the following design patterns does node use?

circle(5)); Because of this behaviour of require , singletons are probably the most common Node. js design patterns among the modules in NPM. npm is used by open source developers from all around the world to share and borrow code, as well as many businesses.

How do callbacks work in node?

js Callback Concept. A callback is a function which is called when a task is completed, thus helps in preventing any kind of blocking and a callback function allows other code to run in the meantime. Callback is called when task get completed and is asynchronous equivalent for a function.


1 Answers

JavaScript will never interrupt a function to run a different function.

The "file has been read" handler will be queued until the JavaScript event loop is free.

like image 122
Quentin Avatar answered Oct 05 '22 23:10

Quentin