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

122
Views
Order of execution Javascript

I have this code:

setTimeout(function timeout() {
    console.log('timeout');
}, 0);

let p = new Promise(function(resolve, reject) {
    console.log('create promise');
    resolve();
});

p.then(function(){
    console.log('execute promise');
});

console.log('end');

I get this order when execute the code:

  • create promise
  • end
  • execute promise
  • timeout


Question: Why create promise is executed first? I expect to execute first end, because it is the only one synchrone code so it should be first executed.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The callback passed to the Promise constructor is executed immediately and synchronously. But it is possible to start an asynchronous task in a Promise callback. Then the Promise resolves after the asynchronous task has completed. This is the primary use-case of Promises.

In your case there is no asynchronous task started, so all your cody is synchronous.

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!