jonas :
I am trying to make a timer, and trying to exit from the callback hell that is happening inside the code I am writing, this is a part from the code I have written, the problem is that I am not receiving the feedback from the promise, so no resolve message, no reject message. what is the problem?
var timer = 15;
var startTimer = (timer) => {
return new Promise((resolve, reject)=>{
if(resolve){
var countDown = setInterval(() => {
console.log(timer);
timer--;
if (timer == 0) {
clearInterval(countDown);
return "YOU ARE LOSER";
}
}, 1000);
}
if(reject){
return "sorry something went wrong!";
}
})
}
startTimer(timer)
.then(message =>{
console.log(message);
//the message should be "You are loser!".
})
.catch(message =>{
console.log(message);
})
Shoejep :
You're using promises wrong, take a look at this friendly tutorial.
You resolve or reject the value that you want to return.
var timer = 15;
var startTimer = (timer) => {
return new Promise((resolve, reject) => {
try {
var countDown = setInterval(() => {
console.log(timer);
timer--;
if (timer == 0) {
clearInterval(countDown);
resolve("YOU ARE LOSER");
}
}, 1000);
} catch (err) {
reject("sorry something went wrong!");
}
})
}
startTimer(timer)
.then(message => {
console.log(message);
})
.catch(message => {
console.log(message);
})
Simplified version without promises
var timer = 10;
var countDown = 0;
var startTimer = fn => setInterval(() => {
console.log(timer);
if (--timer === 0)
{
clearInterval(countDown);
console.log("You lose");
if(fn)
fn();
}
}, 500);
function onTimerFinished() {
console.log("Timer has finished");
}
try {
countDown = startTimer(onTimerFinished);
} catch (err) {
console.error(err);
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=302376&siteId=1