The service method call does not occur synchronously

In my OrderServer class, I am utilizing an OrderService to connect to a database and retrieve data every minute. The communication with the web app is handled through SocketIO. Here is a snippet of the code:

export class OrderServer {
// some required fields

    constructor() {
        console.log("Initializing OrderServer...");
        this._orderService = new OrderService();
        // additional setup
        this.listen();
    }

    private listen(): void {
        this.server.listen(this.port, () => {
        });

        this.io.on('connect', (socket: socketIo.Socket) => {
            setInterval(() => {
                let orders : Order[] = this._orderService.getNewNProcessingOrders();
                console.log("Orders : " + orders);
            }, 60000);
        });
    }
}

I have the code for OrderService as well but it's not necessary to include it at the moment. If needed, I can provide it later.

The issue arises with the ordering of console log statements in the getNewNProcessingOrders() method. Despite calling getNewNProcessingOrders() first in the listen method, the corresponding console log statement executes after the one in listen(). This raises the question of why this call is non-blocking. I've searched for documentation on this matter without success, specifically dealing with scenarios where service method calls are non-blocking.

Answer №1

If blocking were to occur, your entire application would come to a standstill, waiting for the server's response before proceeding, given that JavaScript operates on a single thread.

This is precisely why promises, observables, and other asynchronous mechanisms exist: to handle such scenarios. Your service cannot simply return an array of orders; it should instead return an observable or promise, or accept a callback (although I do not recommend the latter).

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

Error encountered in typescript when trying to implement the Material UI theme.palette.type

Just starting out with Material UI and TypeScript, any tips for a newcomer like me? P.S. I'm sorry if my question formatting isn't quite right, this is my first time on Stack Overflow. https://i.stack.imgur.com/CIOEl.jpg https://i.stack.imgur.co ...

The state data is not being properly updated and is getting duplicated

While developing a loop to parse my API data, I encountered an issue where the values obtained were not being captured properly for dynamically loading corresponding components based on their characteristics. The problem arose after implementing useState() ...

Triggering an event through a shared messaging service to update the content of a component

I'm looking for a simple example that will help me understand how I can change the message displayed in my component. I want to trigger a confirmation box with *ngIf and once I confirm the change, I want the original message to be replaced with a new ...

I am continuously receiving the message "Alert: It is important for every child in a list to possess a distinct "key" prop." while working with the <option> list

Having trouble generating unique keys for my elements. I've tried different values and even Math.random() but still can't seem to get it right. I know the key should also be added to the outer element, but in this case, I'm not sure which on ...

Having trouble with clearInterval in React TypeScript?

I have been encountering issues with the clearInterval function in TypeScript for React. I am not sure why the interval is not being cleared. To address this problem, I defined a variable let interval_counter;, and used it as follows: interval_counter = ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Creating an enum from an associative array for restructuring conditions

Hey everyone, I have a situation where my current condition is working fine, but now I need to convert it into an enum. Unfortunately, the enum doesn't seem to work with my existing condition as mentioned by the team lead. Currently, my condition loo ...

Exploring how NestJS can serialize bigint parameters within DTOs

I have data transfer objects (DTOs) with parameters that are of type bigint. However, when I receive these DTOs, the parameters always have a type of string. Here is an example: @Get("") async foo(@Query() query: Foo) { console.log(typeof Foo ...

sass: node_modules/ionic-angular/themes/ionic.variables.scss

Encountered error during the execution of Ionic Cordova build command sass: node_modules/ionic-angular/themes/ionic.functions.scss Full Error: [11:34:50] sass started ... [11:34:51] sass: node_modules/ionic-angular/themes/ionic.functions.scss, line: 35 ...

NPM Package: Accessing resources from within the package

My Current Setup I have recently developed and published an npm package in typescript. This package contains references to font files located within a folder named public/fonts internally. Now, I am in the process of installing this package into an Angul ...

The error message "Property 'data1' is not a valid property on the object type {}"

const Page: NextPage = ({data1}:{data1:any}) => { const [open, setOpen] = React.useState(false); const [data, setData] = React.useState(data1); const handleAddClick = () => { setOpen(true); }; ..... } export async function getServerS ...

reconfigure components by resetting settings on a different component

In the interface, I have a section that displays text along with a unique component titled FilterCriteriaList. This component includes custom buttons that alter their color when clicked. My goal is to reset the settings in the FilterCriteriaList component ...

How can I set ion-option to be selected by tapping instead of having to click OK?

Currently, I am developing a mobile application and have encountered a scenario in which I utilized ion-option with ion-select, resulting in successful functionality. However, I am now aiming to remove the OK/CANCEL button so that users do not need to clic ...

The variable 'minSum' is being referenced before having a value set to it

const arrSort: number[] = arr.sort(); let minSum: number = 0; arrSort.forEach((a, b) => { if(b > 0){ minSum += minSum + a; console.log(b) } }) console.log(minSum); Even though 'minSum' is defined at the top, TypeScript still throws ...

The embedded Twitter widget in the Angular 2+ app is visible only upon initial page load

After implementing the built-in function from Twitter docs into ngAfterViewInit function, my app works flawlessly. However, I encountered an issue where the widget disappears when switching routes. Here is the code that only functions on the initial page ...

Retrieve the parent route component in Angular

I am in the process of developing an Angular 7 application that features nested routes. My goal is to identify the specific component being used by the parent route. While I have managed to achieve this locally, the method fails in a production environment ...

My NPM Install is throwing multiple errors (error number 1). What steps can be taken to troubleshoot and

I'm encountering an issue with my Angular project while trying to run npm install from the package.json file. Here are some details: Node version - 12.13.0 Angular CLI - 7.2.4 gyp ERR! configure error gyp ERR! stack Error: unable to verify the fi ...

There is an issue with the Angular Delete request functionality, however, Postman appears to be

HttpService delete<T>(url: string): Observable<T> { return this.httpClient.delete<T>(`${url}`); } SettingsService deleteTeamMember(companyId: number, userId: number): Observable<void> { return this.httpService.delete< ...

I encountered an error while trying to deploy my next.js project on Vercel - it seems that the module 'react-icons/Fa' cannot be found, along with

I'm currently in the process of deploying my Next.js TypeScript project on Vercel, but I've encountered an error. Can someone please help me with fixing this bug? Should I try running "npm run build" and then push the changes to GitHub again? Tha ...

The data structure of '(string | undefined)[]' cannot be matched with type '[string | undefined]'

I've been working on a TypeScript project and I've encountered the ts(2322) error as my current challenge. Here's a snippet of my code: import { BASE_URL, AIRTABLE_BASE_ID, AIRTABLE_TABLE_STUDENT, AIRTABLE_TABLE_CLASSES, API_KEY, ...