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

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

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 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!