Skip to main content
Waits for a background process to exit and returns its exit code. This is useful for waiting on batch jobs or short-lived processes.

Method Signature

await process.waitForExit(
  timeout?: number
): Promise<WaitForExitResult>
This is a method on the Process object returned by startProcess(), not on the sandbox itself.

Parameters

timeout
number
Maximum time to wait in milliseconds. If not specified, waits indefinitely.

Returns

WaitForExitResult
object

Examples

Wait for process completion

const process = await sandbox.startProcess('python train.py');

const { exitCode } = await process.waitForExit();

if (exitCode === 0) {
  console.log('Training completed successfully');
} else {
  console.log('Training failed with exit code:', exitCode);
}

Wait with timeout

const process = await sandbox.startProcess('npm run build');

try {
  const { exitCode } = await process.waitForExit(30000); // 30 seconds
  console.log('Build completed:', exitCode);
} catch (error) {
  console.error('Build timed out after 30 seconds');
}

Run and wait for batch job

const process = await sandbox.startProcess(
  'python process_data.py',
  { processId: 'data-processor' }
);

console.log('Processing data...');
const { exitCode } = await process.waitForExit();

if (exitCode === 0) {
  const logs = await process.getLogs();
  console.log('Processing complete:', logs.stdout);
}

Handle multiple processes

const processes = await Promise.all([
  sandbox.startProcess('task1.sh'),
  sandbox.startProcess('task2.sh'),
  sandbox.startProcess('task3.sh')
]);

const results = await Promise.all(
  processes.map(p => p.waitForExit())
);

const allSucceeded = results.every(r => r.exitCode === 0);
console.log('All tasks succeeded:', allSucceeded);

Error Handling

Throws ProcessReadyTimeoutError if the timeout is reached before the process exits.
import { ProcessReadyTimeoutError } from '@cloudflare/sandbox';

try {
  await process.waitForExit(5000);
} catch (error) {
  if (error instanceof ProcessReadyTimeoutError) {
    console.log('Process did not exit within timeout');
    await process.kill(); // Clean up
  }
}

Build docs developers (and LLMs) love