Lançado · em melhoria
Guia de JavaScript · 6/6
Por enquanto, este capítulo está disponível apenas em inglês.
A few ideas separate writing JavaScript from understanding it: the event loop that lets a single thread juggle timers and network calls, the callbacks, Promises and async/await built on top of it, closures, and the ever-confusing this.
JavaScript runs your code on one thread. Slow work like network requests, file reads and timers is handled in the background, and when it finishes a callback is queued. Whenever the call stack is empty, the event loop takes the next job off the queue.
There are two queues. Microtasks, such as Promise then callbacks, all run as soon as the current code finishes. Tasks, such as setTimeout callbacks, run one at a time after that.
console.log("1: sync");
setTimeout(() => console.log("4: timeout (task)"), 0);
Promise.resolve().then(() => console.log("3: promise (microtask)"));
console.log("2: sync");
// prints 1, 2, 3, 4Even with a delay of 0, a timeout waits for the current code and every pending microtask. Conversely, long synchronous work freezes the page or stalls a server.
The oldest async style passes a function to call when work is done. Classic Node.js APIs use error-first callbacks: the error comes first, the result second.
import { readFile } from "node:fs";
readFile("notes.txt", "utf8", (error, text) => {
if (error) {
console.error("read failed:", error.message);
return;
}
console.log(text.length, "characters");
});Nest a few of these and indentation grows while error handling scatters. Promises fix that.
A Promise stands for a value that will arrive later. It settles once, from pending to either fulfilled or rejected. Chain then for results, catch for errors and finally for cleanup.
function delay(ms, value) {
return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
delay(300, "done")
.then((value) => value.toUpperCase())
.then((upper) => console.log(upper))
.catch((error) => console.error(error))
.finally(() => console.log("finished"));
const both = await Promise.all([delay(100, "a"), delay(200, "b")]); // ["a", "b"]
const first = await Promise.race([delay(100, "fast"), delay(500, "slow")]); // "fast"| Combinator | Settles with |
|---|---|
Promise.all | All results, or the first rejection |
Promise.allSettled | The outcome of every Promise |
Promise.race |
| Whichever settles first, success or failure |
Promise.any | The first success, or AggregateError if all fail |
An async function always returns a Promise, and await pauses it until a Promise settles. The result reads top to bottom like synchronous code. Independent operations should start together with Promise.all instead of being awaited one by one.
async function loadDashboard(userId) {
// sequential: the second call needs the first result
const user = await getUser(userId);
const team = await getTeam(user.teamId);
// parallel: these do not depend on each other
const [posts, alerts] = await Promise.all([getPosts(userId), getAlerts(userId)]);
return { user, team, posts, alerts };
}fetch is built into browsers and recent Node.js. The catch: a 404 or 500 response does not reject the Promise. Only network failures do, so check response.ok yourself.
async function getJson(url) {
const response = await fetch(url, {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(5000), // give up after 5 seconds
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${url}`);
}
return response.json();
}
try {
const repo = await getJson("https://api.github.com/repos/nodejs/node");
console.log(repo.full_name, repo.stargazers_count);
} catch (error) {
console.error("request failed:", error.message);
}A function remembers the variables in scope where it was created, even after the outer function returns. That is a closure, and it keeps state private.
function createCounter() {
let count = 0; // unreachable from outside
return {
increment: () => ++count,
reset: () => { count = 0; },
};
}
const counter = createCounter();
counter.increment();
console.log(counter.increment()); // 2
// let creates a fresh binding per iteration
for (let i = 0; i < 3; i += 1) {
setTimeout(() => console.log(i), 0); // 0, 1, 2
}this is decided by how a function is called, not where it is written. Call obj.method() and this is obj; pull the method out and call it alone and the link is gone. Arrow functions have no this of their own and use the one from the surrounding scope.
const timer = {
seconds: 0,
start() {
// the arrow function reuses start's this (timer)
setInterval(() => {
this.seconds += 1;
}, 1000);
},
report() {
return `${this.seconds}s`;
},
};
const report = timer.report;
// report(); // this is no longer timer: throws or returns garbage
const bound = timer.report.bind(timer);
console.log(bound()); // "0s"async/await to callbacks, and run independent work with Promise.all.fetch does not reject on HTTP errors, so check response.ok.this depends on the call, so pin it with arrow functions or bind.
0 comentários
Fazer login · Faça login para deixar um comentário.
Seja o primeiro a comentar.