A Promise describes a task that can eventually succeed or fail. A call such as fetch initially returns a Promise rather than the data itself. async makes a function asynchronous. await waits inside that function for a result. This does not guarantee parallel CPU processing.
01Start a delayed task
setTimeout schedules later execution. The Promise then resolves with the name. This example works without a network so you can observe the workflow independently of a server.
function loadName() {
return new Promise((resolve) => {
setTimeout(() => resolve('House'), 100);
});
}
try {
const name = await loadName();
console.log(name);
} catch (error) {
console.error('Loading failed:', error.message);
}
Run / check
node async.mjs02Use the result
await loadName() produces House after the delay. Without await you would hold the Promise itself. During a real network task, the interface can remain responsive. An old request completing later must not automatically replace newer displayed data.
03Try the failure path
Replace resolve("House") with reject(new Error("Unavailable")) and add reject as the second Promise callback parameter. catch receives the error. finally would be a place for cleanup needed on both success and failure.
After about 100 milliseconds: House
Your exercise
Start two independent loadName calls using Promise.all. What does the result look like?
Show the solution and explanation
const names = await Promise.all([loadName(), loadName()]) produces ["House", "House"]. The order follows the inputs. If one task fails, Promise.all rejects. This does not automatically cancel the other task.
Project context and sources
The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.