I've read some articles about Promises and async/await in JavaScript to understand its point, but yet have not completely comprehended it; so, I'll explain an example here and want you to help me to comprehend the mechanism. The following code are in NestJS.
Here is my auth.service.ts:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UserRepository } from './user.repository';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository
) {}
createUser(): void {
this.userRepository.createUser();
console.log('Here I want to do some other works simultaneously while this.userRepository.createUser() is also processing');
}
}
Here is my user.repository.ts:
import { EntityRepository, Repository } from 'typeorm';
import { User } from './user.entity';
@EntityRepository(User)
export class UserRepository extends Repository<User> {
async createUser(): Promise<void> {
await this.makeUser();
}
async makeUser(): Promise<void> {
return new Promise((resolve, reject) => {
// Simulating making a user which will take some time
let x = 1;
for (let i = 0; i < 1000000000; i++) {
x++;
}
console.log('User Created');
resolve();
});
}
}
What I expect based on the above code and what I have learned so far, is that the line console.log('Here I want to do some other works simultaneously...') to work before completion of the line this.userRepository.createUser(), but this does not happen and I get "User Created" logged first and then I get "Here I want to do some other works simultaneously...".
Where am I wrong?
forloop is blocking the execution of all other code paths until it completes.