Search code examples
javascriptnode.jsnode-postgres

Finally block is running before Promise.all() finished


I'm working on a script to seed my database but am having issues with my node-pg connection being terminated before my rebuild function is finished.

const rebuildDB = async () => {
  try {
    client.connect();
    await dropTables();
    await createTables();
    await Promise.all(employees.map(createEmployee), customers.map(createCustomer));
  } catch (err) {
    console.log(err);
  } finally {
    client.end();
  }
};

rebuildDB();

When I remove the finally block everything runs correctly. If i leave it, the createEmployee function will execute but the connection will be terminated before createCustomer() is able to execute.

Any suggestions?


Solution

  • Reposting my comment as a proper answer (and adding to it):

    There are two issues. The main one, which you asked about, is that you're calling Promise.all incorrectly. It accepts only a single argument, not multiple arguments, so it's ignoring the promises from the second argument entirely. You want to pass in a single iterable (probably an array in this case).

    The other problem is that you don't want client.connect() inside the try, since you don't want to call client.end() if client.connect() throws.

    So:

    const rebuildDB = async () => {
        // This shouldn't be *inside* the `try`, since you don't want to call
        // `client.end()` if this fails
        client.connect();  // <=== Does this need an await? It doesn't have one in your question...
        try {
            await dropTables();
            await createTables();
            // Pass a single array to `Promise.all`
            await Promise.all([...employees.map(createEmployee), ...customers.map(createCustomer)]);
        } catch (err) {
            console.log(err);
        } finally {
            client.end();
        }
    };
    
    rebuildDB();