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

75
Views
How to count number using promise

I want to counter some number using promise that the result is 1,2,3,done and I have coded it like this

const state = true

const count = new Promise((resolve, reject) => {
  if (state) {
    resolve("counter work")
    for (let i = 1; i <= 3; i++) {
      setTimeout(() => {
        console.log(i);
      }, 1000);
    }
    console.log("done");
  } else {
    reject("counter not work")
  }
})
count
  .then((response) => console.log("success", response))
  .catch((response) => console.log("failed", response));

and the result is : done,1,2,3 but i want the result 1,2,3,done

can anybody tell why my code have result like that and how the code should it is

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

0

The early resolve aside, the reason for "done" being logged first is that you're calling setTimeout in a loop. setTimeout doesn't block execution, it queues a callback to be run after some time and returns immediately. So you're just creating three Timeouts that'll all fire about a second after you've exited the loop and logged "done".

To create a timer, you could conditionally call setTimeout within the callback:

new Promise((resolve, reject) => {
  let i = 0
  function increment () {
    i++
    console.log(i)
    if (i < 3) {
      setTimeout(increment, 1000)
    } else {
      console.log('done')
      resolve() // to mark the promise as completed
    }
  }
  setTimeout(increment, 1000)
})
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!