I have a class OrderServer where I am calling a service OrderService which connects to DB and fetch the data. Data gathering happens every 1-minute. OrderServer use SocketIO to communicate with the webapp. code is as follows:
export class OrderServer {
// some required fields
constructor() {
console.log("in OrderServer Constructor...");
this._orderService = new OrderService();
// some other initiations and calls
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 OrderService code as well but not putting it here as it doesnt seem required right now. If need be I will put it.
The problem is there is one console log statement is in getNewNProcessingOrders(). If you have noticed there is console.log statement after calling getNewNProcessingOrders() in listen method.
I expect, Console log statement in getNewNProcessingOrders() method should execute first and then the console log statment in listen() but its other way around.
Why is this._orderService.getNewNProcessingOrders(); is not blocking? I tried finding documentation but couldnt find specific to this issue where service method calls are not blocable.
Because if it was blocking, your whole app would freeze, doing nothing until the server sends back the result, since everything in JavaScript is executed in a single thread.
That's why promises, observables etc. exist: to deal with asynchrony. Your service can't possibly return an array of orders. It should return an observable or a promise. or take a callback (although I wouldn't advise that).