我正在尝试制作一个计时器,并尝试退出我正在编写的代码中发生的回调 hell ,这是我编写的代码的一部分,问题是我没有收到反馈来自 promise ,所以没有解决消息,没有拒绝消息。 有什么问题吗?
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);
})
最佳答案
resolve
和 reject
是要调用的函数。 resolve
用于异步操作完成时,reject
用于发生错误时。调用这些函数时,您可以提供一个值以沿着 Promise 链传播。
var count = 5
var startTimer = (count)=>{
return new Promise((resolve,reject)=>{
try {
var intervalId = setInterval(()=>{
if(count) {
console.log(count--)
return
}
clearInterval(intervalId)
resolve( "YOU ARE LOSER")
}, 1000)
} catch {
reject('sorry something went wrong!')
}
})
}
startTimer(count)
.then((result)=>{ console.log(result) })
.catch((err)=>{ console.log(err) })
关于javascript - 函数内设置的间隔必须返回解析消息或拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60621184/