Skip to content

ORM does not flush anything when used with Promise.all() #2934

@andrew-sol

Description

@andrew-sol

Describe the bug
Imagine a simple User entity with just id and username fields.
We need to save a bunch of users using Promise.all().

The users table should be empty before running the script below.

The script:

async run() {
  const users = [
    { username: 'A' },
    { username: 'B' },
    { username: 'C' },
    { username: 'D' },
  ];

  await Promise.all(users.map(async (userData) => this.saveUser(userData)));
}

async saveUser({ username }): Promise<User> {
  const userRepo = getEntityManager().getRepository(User);

  // This query is required. We need another 'await' before 'persistAndFlush' to trigger the bug.
  let user = await userRepo.findOne({ username });

  if (!user) {
    user = new User();
    user.username = username;

    await userRepo.persistAndFlush(user);
  }

  console.log('User ID:', user.id);

  return user;
}

Console output:

[query] select "u0".* from "users" as "u0" where "u0"."username" = 'A' limit 1 [took 7 ms]
[query] select "u0".* from "users" as "u0" where "u0"."username" = 'C' limit 1 [took 13 ms]
[query] select "u0".* from "users" as "u0" where "u0"."username" = 'B' limit 1 [took 14 ms]
[query] begin
[query] select "u0".* from "users" as "u0" where "u0"."username" = 'D' limit 1 [took 47 ms]
[query] insert into "users" ("created_at", "updated_at", "username") values ('2022-03-21T13:23:01.398Z', '2022-03-21T13:23:01.398Z', 'A') returning "id", "created_at", "updated_at" [took 4 ms]
[query] commit
User ID: undefined
User ID: undefined
User ID: undefined
User ID: 1

And in the database we have only 1 user created (user A).

But everything works fine if we remove this line:

let user = await userRepo.findOne({ username });

Versions

Dependency Version
node 16.13.2
typescript -
mikro-orm 5.1.1
your-driver postgres

Metadata

Metadata

Assignees

No one assigned

    Labels

    wontfixThis will not be worked on

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions