Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
JavaScript promise blocking code execution

Could someone try and help me to understand why the first function is non-blocking while the second one blocks the rest of the code? Isn't Promise.resolve the same as resolving from a new Promise? I can't quite wrap my head around it.

function blockingCode() {
  return new Promise((resolve, reject) => {
    for (let i = 0; i < 2500000000; i++) {
      // Doing nothing...
    }
    resolve('ping');
  });
}

function nonBlockingCode() {
  return Promise.resolve().then(() => {
    for (let i = 0; i < 2500000000; i++) {
      // Doing nothing...
    }
    return 'pong';
  });
}

console.time('non-blocking');
nonBlockingCode().then((message) => console.log(message));
console.timeEnd('non-blocking');

// console.time('blocking');
// blockingCode().then((message) => console.log(message));
// console.timeEnd('blocking');

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The two functions are actually blocking.

You have the illusion that the second one isn't blocking because calling Promise.resolve().then() adds one more round to the event loop, so console.timeEnd('non-blocking'); is reached before the code inside your promise even starts.

You will notice that both function block if you fix your code like this:

console.time('non-blocking');
nonBlockingCode()
.then((message) => console.log(message))
.then(() => console.timeEnd('non-blocking'));

Note that a promise is intended not to block when the time-consuming logic inside the promise is delegated to a third-party, and you just wait for the result (e.g. when a client does a call to a remote database, a remote web server, etc.).

If you are having a hard time with promises and then logic, have a look at the async / await syntax, I find it much easier to understand.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda