SetInterval内部承诺。为什么这个诺言立即解决?

时间:2018-09-04 07:11:36

标签: javascript promise setinterval

我试图了解诺言如何实现

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

由于某种原因,我立即看到startedresolved警报{br /> 然后以间隔1秒state 0state 2state 4finished为间隔。
为什么诺言立即解决? 如何在直接执行resolve()之前阻止承诺的解决?

1 个答案:

答案 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'))