我试图了解诺言如何实现
let promise = new Promise( (resolve, reject) => {
alert("started");
let num = 0;
let interval = setInterval(() => {
alert(`state ${num}`);
num += 2;
if (num > 4) {
clearInterval(interval);
alert("finished");
resolve()
}
}, 1000)
});
promise.then(alert('resolved'))
由于某种原因,我立即看到started
,resolved
警报{br />
然后以间隔1秒state 0
,state 2
,state 4
和finished
为间隔。
为什么诺言立即解决?
如何在直接执行resolve()
之前阻止承诺的解决?
答案 0 :(得分:1)
.then
接受 function 作为参数,而不是简单的语句或表达式(除非所述表达式求值为函数)。改用它:
promise.then(() => console.log('resolved'))
演示:
let promise = new Promise( (resolve, reject) => {
console.log("started");
let num = 0;
let interval = setInterval(() => {
console.log(`state ${num}`);
num += 2;
if (num > 4) {
clearInterval(interval);
console.log("finished");
resolve()
}
}, 1000)
});
promise.then(() => console.log('resolved'))