#asynchronous function does not finish if not awaited

1 messages · Page 1 of 1 (latest)

next plank
#
async function test() {
    const proc = Bun.spawn(['echo', 'cheese'], {
        cwd: process.cwd(),
        stdout: 'inherit',
        stderr: 'inherit'
    });

    await proc.exited;
    console.log(proc.exitCode);
}

test();
console.log('foo');

In the above code, an asynchronous function is invoked which spawns a process. When the process exits, the exit code should be printed.

However, the lack of await on the call to test() appears to make this short-circuit, and anything after the internal await proc.exited is never processed. Instead, once the process is finished, the parent process terminates.

Adding an await to the call makes this behave as expected.

async function test() {
    const proc = Bun.spawn(['echo', 'cheese'], {
        cwd: process.cwd(),
        stdout: 'inherit',
        stderr: 'inherit'
    });

    await proc.exited;
    console.log(proc.exitCode);
}

await test();
console.log('foo');

From my understanding, calling test() without await should still exhibit the same behaviour, with the exception that foo is not printed until after the promise resolves in the seond snippet.

untold path
#

This is a normal behaviour. In fact in the first example you will see the output:

foo
cheese
#

In the second you will see cheese first and a 0 in another line.

willow lagoon
#

bun is exiting before 0 can be printed. my guess is after the main module is done running we arent checking if there are async tasks running

#

i feel this wouldve already been reporetd but can you open an issue for this

untold path
#

Oh yes, I see. I replicated your code in node:

import { spawn } from "node:child_process";

function test() {
  return new Promise((resolve, reject) => {
    const ps = spawn("echo", ["cheese"]);
    ps.stdout.on("data", (data) => {
      console.log(data.toString());
    });

    ps.stderr.on("data", (data) => {
      reject(data.toString());
    });

    ps.on("close", (code) => {
      if (code !== 0) {
        return reject(`ps process exited with code ${code}`);
      }

      resolve(code);
      console.log(code);
    });
  });
}

test();
console.log("foo");

And return:

oo
cheese

0
cheese

0
foo

Report on issues.