我正在从事以下JS练习。 promise.then
不会以某种方式被触发。我在节点上使用VS Code。我想知道为什么或做错了什么。请参阅下面的代码。谢谢!
更新:经过一些测试,我意识到第一个回调无法解析b / c,我有一个无限的while
循环。当while循环不存在时,它起作用了。
一个假设是,由于JS是single threaded,while
循环会占用所有资源,因此异步功能永远不会有解决的机会。 ..听起来正确吗?
function mySetInterval(callback, interval) {
let prevTime = new Date().getTime();
let finish = false;
callback().then((msg) => {
console.log('This callback is never triggered ', msg);
finish = true;
})
.catch((msg)=> {
console.log('This callback is never triggered either ', msg);
});
while (true) {
let newTime = new Date().getTime();
if ((prevTime + interval) <= newTime){
if (finish) {
finish = false;
callback()
.then((successMsg) => {
finish = true;
console.log('Of course this callback is never triggered, cuz the first one is never triggered ', successMsg);
});
}
prevTime = newTime;
}
}
}
mySetInterval(() => {
return new Promise((resolve, reject) => {
resolve(new Date().getTime());
});
}, 500);