Reputation: 3
I have a problem. My code doesn't work. It doesn't display the last essage in the console.log (the "end"). I use a setTimeout promise to do one thing every 3000ms. Here is my promise function setTimeOut
function delay(message){
return new Promise(() => setTimeout(function () {
console.log(message)
}, 3000))
}
That I use in an async function in my code :
async () => {
while (true) {
console.log("Start")
await delay("No")
console.log("End")
}
}
I make my code more easier (without all the conditions and the functions that I have to call) because I think I've missed something in my understanding of the promise maybe. What am i doing wrong?
Could you please help me for this?
Upvotes: 0
Views: 2639
Reputation: 5815
Your promise in delay
/timeout
function never resolves.
Here's how it will work. Note the resolve
parameter of the promise callback.
function delay(message) {
return new Promise((resolve) => setTimeout(function () {
console.log(message);
resolve();
}, 3000))
}
(async () => {
while (true) {
console.log("Start")
await delay("No")
console.log("End")
}
})();
Upvotes: 3