Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de JavaScript
JavaScript
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts: Async and Closures
Debates

Guía de JavaScript · 6/6

Key Concepts: Async and Closures

Por ahora, este capítulo solo está disponible en 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.

The event loop

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, 4

Even 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.

Callbacks

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.

Promises

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"
CombinatorSettles with
Promise.allAll results, or the first rejection
Promise.allSettledThe outcome of every Promise
Promise.race
¿Tienes preguntas sobre este capítulo?
Capítulo anteriorErrors and Testing
Whichever settles first, success or failure
Promise.anyThe first success, or AggregateError if all fail

async and await

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

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);
}

Closures

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

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"

Summary

  • One thread plus the event loop handles async work; microtasks (Promises) run before tasks (timers).
  • Prefer Promises and async/await to callbacks, and run independent work with Promise.all.
  • fetch does not reject on HTTP errors, so check response.ok.
  • Closures keep state private; this depends on the call, so pin it with arrow functions or bind.

Further reading

  • MDN JavaScript Guide
  • MDN JavaScript Reference
  • MDN: Using promises
  • Node.js API docs
  • npm Docs
  • ECMAScript specification, the standard itself

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.