Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda