Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!