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

183
Vistas
How to convert async/await code to blocking code in javascript?

I know blocking the event loop is bad and the consequences of that. But even the native fs module provides some sync functions for some purposes, for example, CLIs using fs.readFileSync.

I'd like to convert the following async-await code to blocking code.

let value = undefined;

function setup() {
  return new Promise((resolve) => {
    setTimeout(() => {
      value = "**value**";
      resolve();
    });
  });
}

// need to convert below function to blocking
async function getValue() {
  await setup();
  return value;
}

console.log(await getValue()); // top level await OK

Assuming it is blocking, we can then call it like

getValue(); // without await or .then

I tried it like this. But it is not working.

function getValue() {
  setup();
  while (!value) {
    // wait until we get value
  }

  return value;
}

console.log(getValue())

How can I achieve this?

(The fs.readFileSync is blocking. Is there any way we can use the technique used by readFileSync)

Edit

Related thread: Convert asynchronous/callback method to blocking/synchronous method

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

0

How can I achieve this?

You change language.

Seriously: JavaScript is (more or less, there are many caveats there) single threaded. Your callback code should be processed by the same thread you intend to block.

There is NO way you can achieve this: it's impossible.

So, either you change your language (in C# or Java you can spin up a thread and block it as you wish, while other threads do some work), or you change requirements.

I suspect this last option is the real solution to your alleged problem. Now, what is that you really need to do?

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