Inquiry regarding the functioning of code execution and the characteristics of JavaScript's blocking and non-blocking nature

Having code that resembles the snippet below, I am uncertain about the order of execution it follows. Currently, it seems to run in a non-blocking manner:

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

However, there have been instances where it operated as:

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

Since res.on('data') acts as a socket event listener handled on a separate server and is beyond my control, I worry that the callback might get invoked amidst res.on(). Is it possible for the callback to interrupt the ongoing res.on() process if called midway through?


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 №1

In order for JavaScript code to switch midway within a function, it must include a yield instruction.

If your current function lacks this instruction, it will not be able to switch midway.

Although yield is not frequently used, callbacks (such as async/await) are commonly used instead. These provide a more organized way of handling asynchronous operations and error handling compared to a long chain of callbacks.

While the use of self.submit() may trigger a callback, the res.on() function itself does not pause execution midway.

It's important to remember that JavaScript is still event-driven and single-threaded, meaning only one function runs at any given time.

If the order in which functions execute doesn't matter (e.g., callback -> res.on() or res.on() -> callback), then you're all set.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most effective method for filtering a table using both column-specific and global filters?

Looking for the most efficient way to filter a large chunk of JSON data client-side using a table? Each header has an input filter where users can enter a string to filter that specific property. There is also a global filter for free text search. If you ...

Animating the rotation of a Three JS mesh to a set of precise coordinates within space

Currently, I am working on a project involving an airplane model that is initially facing a default location along the Z axis. My goal is to create a functionality where, upon clicking a button, the airplane will smoothly turn towards a specific vector at ...

Retrieve the parent category based on the selection of a child category in the dropdown

Currently, I have code implemented that displays all my categories within a dropdown menu. If you would like to see it in action, please visit this link: While the code works smoothly for parent categories, there seems to be an issue with recognizing the ...

What is the most effective approach for returning varying object types based on conditions in JavaScript?

Currently, I am working on creating a function to validate input arguments. However, I am unsure if the method I am using is considered best practice. The validation function I have created looks like this: const isValidStudyId = (id) => { if (valida ...

The raycaster is experiencing issues when used with multiple cameras in the Three.js library

I am currently developing an application similar to the threeJs editor. In this project, I have implemented four different cameras, each with unique names and positions. Here is an example of one of the cameras: cameras['home'] = new THREE.Combi ...

Problem arises when attempting to slice an array that is defined in the parent component

Seems like a simple mistake, but here's what happened: In the main parent component, I have an array defined: ... <object-list-grid v-bind:objects="objectsList" ></object-list-grid> ... data() { return { ... ...

Replicating a Div Click Event using Enzyme and React

I've recently started working with Enzyme and writing tests for an application developed by a team. One of the test cases involves simulating a click on an element that toggles the display of a check-mark image. The application consists of a list wher ...

The deletion of property '1' from the [object Array] is not possible

How to Retrieve a List in My Components Using Input : @Input() usersInput: Section[]; export interface Section { displayName: string; userId: number; title: number; } Here is the Value List : 0: displayName: "بدون نام" ...

Ways to run evaluations on 'private' functions within an angular service using Karma and Jasmine

In my Angular application, I have a BracketService that consists of various functions for comparing weights and creating brackets based on weight groups. The service includes functions like compareByWeight, filterWeightGroup, and createBracketsByWeightGrou ...

Evaluating the similarity between a Guild ID and a matching string

Currently, I am in the process of creating a bot with a unique feature - a config command that enables users to customize specific functionalities within their servers. This customization is facilitated through a straightforward JSON file named config.json ...

Utilizing a Material UI custom theme in React with Typescript: A step-by-step guide

Upon using the tool , I received a js file and a json file following the paths mentioned on the theme generator page: // src/ui/theme/index.js /* src/ui/theme/theme.json */ The files operate smoothly when left with the .js extension. However, when I attem ...

How should a table be linked to two other tables in a situation where both tables could potentially be the right choice?

Introduction In the realm of database design, the challenge arises when attempting to create a system where a customer can either be an individual or a company, but not both. The question at hand is how best to construct the relationship between three key ...

using regular expressions to find unclosed font tags that match on a single line

Even though regex is not typically recommended for parsing HTML, in this case we are dealing with a single line string input to a function. For example: <font color = "#ff0000"> hello </font>. I want the regex pattern to match only if the tag ...

Challenges stemming from join operations and the implementation of where clauses

I have three tables named Action, ActionType, and Member. I am attempting to display a table that shows the count of different ActionTypes in a specific status (a property of the Action table) for a particular Member. Essentially, I want one row for each A ...

Learn the process of extracting text from a doc/docx file using the fs api in node.js

I have found that the code provided is effective in extracting content from doc/docs type documents. However, I am only interested in extracting strings and not images. When the code encounters a document containing images, it generates a large amount of ...

Assistance needed in getting a Database configured

In planning my website, I anticipate offering a wide variety of products across different domains. My dilemma is whether to centralize all product data in one database with site IDs for categorization or to create separate tables or databases for each sit ...

Assign a value to an input element with JavaScript and retrieve the value using PHP

Below is a form and input element that can be found in the cart.php file: <form id="cartform" action="cart.php?action=update&pd=<?php echo $row['product_id'] ?>" name="form1" method="post"> <?php $query = "select * from ca ...

AngularJS: excessive number of event listeners in the view leading to extended loading times

Experiencing an issue with the Angular view when loading the view for the second time. Input: The view loads a list of 1500 items All 1500 items are displayed in a table using ng-repeat with a filter No $watch is used in the view Problem description: ...

Need help fixing a javascript issue: TypeError - Unable to access property 'hash' as it is undefined

Recently, an upgrade to webpack 5.65.0 caused issues with @react-pdf/renderer. I found a potential fix on a GitHub Issue here. Despite trying the suggested "fix," I encountered the same error as described in this Stack Overflow post, but the solution provi ...

Issues with Mysql2 disrupting the routing system

Currently facing an issue with mysql2 in the backend, as it seems to be interfering with my routes during production. Here is a snippet of my server file: const express = require('express') const app = express() const PORT = process.env.PORT || 5 ...