Node.js Async and Await
An async function returns a promise. await makes a dependency readable, while try/finally keeps cleanup visible on both success and failure.
How it works
Only await tasks that genuinely depend on an earlier result. Independent work can be coordinated deliberately, but starting everything at once can overload a resource. A finally block should release what this scope owns; do not suppress the original error by throwing an unrelated cleanup failure without a policy. The controlled fixture below records the lifecycle so that a rejected operation is still shown to finish its cleanup path.
Run the code
Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as async-await.mjs in a separate empty exercises folder and run node async-await.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.
Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.
Example
const events = [];
async function inspectKit(fail) {
events.push('open');
try {
await Promise.resolve();
if (fail) throw new Error('Inspection failed');
return 'ready';
} finally {
events.push('close');
}
}
try {
await inspectKit(true);
} catch (error) {
console.log(error.message);
}
console.log(events.join(' -> '));
Expected result
Inspection failed open -> close
The failed inspection still reaches close. The example has a logical resource rather than a real file descriptor, which keeps the lifecycle rule easy to inspect before the file and socket lessons apply it to actual owned handles.
Use the Node.js API reference for the precise version contract.