Promises and Async/Await
Some operations — fetching data from a server, reading a file, waiting on a timer — don't finish immediately. JavaScript handles this with a Promise: a value representing something that will complete later, either successfully or with an error.
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
console.log("Starting...");
delay(100).then(() => {
console.log("100ms have passed");
});Starting... 100ms have passed
delay(100) returns a Promise immediately, without blocking anything — "Starting..." prints right away. .then() registers a function to run once the promise resolves, which happens 100ms later when the timer finishes.
async/await — writing async code that reads like synchronous code
await pauses a function at that line until the promise resolves, without blocking the rest of the program — it just makes asynchronous code read top to bottom, instead of nesting callbacks inside .then().
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function main() {
console.log("Starting...");
await delay(100);
console.log("100ms have passed");
}
main();Starting... 100ms have passed
Same result as the .then() version above, but async/await is generally considered easier to read once you have more than one asynchronous step in a row. A function marked async always returns a Promise, and await can only be used inside one.
Next: modules and the standard library — organizing code across files, and what's built in.
Practice exercise
Write an async function getValue() that returns 42, then await it inside another async function and print the result.