Top-level await with Promise.all
Two simulated API calls start together and are awaited at the top level of the script. Because they run concurrently, the total wait is set by the slower call, not the sum of both. Expected output: "Grace has 2 posts", then "both resolved after about 500 ms".
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const started = Date.now();
const [user, posts] = await Promise.all([
delay(300, { id: 7, name: "Grace" }),
delay(500, ["Hello", "Async"]),
]);
console.log(user.name, "has", posts.length, "posts");
console.log(`both resolved after about ${Math.round((Date.now() - started) / 100) * 100} ms`);
Grouping records with reduce
A common data-shaping task: total each customer's orders with reduce and the nullish coalescing operator. Objects passed to console.log print as indented JSON, so the first line of output is {"ana": 162.5, "ben": 19.99} spread over four lines, followed by one padded line per customer.
const orders = [
{ id: 1, customer: "ana", total: 42.5 },
{ id: 2, customer: "ben", total: 19.99 },
{ id: 3, customer: "ana", total: 120 },
];
const totals = orders.reduce((acc, { customer, total }) => {
acc[customer] = (acc[customer] ?? 0) + total;
return acc;
}, {});
console.log(totals);
for (const [name, sum] of Object.entries(totals)) {
console.log(`${name.padEnd(5)} ${sum.toFixed(2)}`);
}
What the Node.js shim provides
Prints the emulated process values, round-trips a string through the minimal Buffer, and shows the error that every require() call raises. console.error output is shown in red, and the script carries on afterwards, which is why the fetch check still prints true.
console.log("platform:", process.platform);
console.log("env:", process.env);
console.log(Buffer.from("héllo").toString());
try {
require("fs");
} catch (error) {
console.error(error.message);
}
console.log("fetch available:", typeof fetch === "function");