Question about code execution and the nature of javascript blocking/ non blocking

Tags: , , ,



Basically I have something similar to the code below and I’m not entirely sure what order of execution is always going to happen. Right now I suppose it executes in a non blocking fashion, being

func() -> self.db.createEntry() -> res.on() -> callback -> self.submit()

But I’ve had times that it’s

func() -> self.db.createEntry() -> callback -> res.on() -> self.submit()

I have no control over when res.on('data') is called because it is a socket event listener and is handled on a separate server. I guess that I’m afraid that the callback is going to be called in the middle of res.on() is that something that could happen? Say res.on() is right in the middle of execution would the callback be able to interrupt that?

const func = function(){

self.db.createEntry(self.arg, self.arg1, function(response){
    if(response){
        self.arg = response
        self.state.wait = false
        if(self.state.wait){
            self.submit()
        }
    }
});

res.on('data', function(data) {
    data = parse(data);
    if(!data.contentId){
        self.state.wait = true;
        self.state.data = data
    }
    else {
        self.submit(data);
    }
});

}

func()

db.prototype.createEntry = function(arg, arg1, callback) {
    self.connect();
    self.connection.query('INSERT INTO table_name SET ?', arg, function(err, results, fields) {
        if(err) {
            self.disconnect();
            callback()
        }
        else {    
            self.disconnect();
            callback(results)
        }
    });
}

Answer

The only way for JavaScript code to switch midway in a function is because of a yield instruction.

Your current function doesn’t include such.

yield is also rarely used. Instead we use callbacks (async/await code are callbacks on steroids—syntax sugar making it a lot easier to write code without a ton a inline functions used to handle a long chain of callbacks and much easier way to handle errors too).

The self.submit() will generate such a callback, but the res.on() itself is not going to stop midway.

Keep in mind that JavaScript is still event driven and it does not use multiple threads. So only one function is executed at a time.

If the order (callback -> res.on() or res.on() -> callback) does not matter, then you’re good to go.



Source: stackoverflow