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
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)
})