I'm struggling to understand why my promise is not working as expected and how to resolve the issue. Here is the code snippet:
let count = 0;
function onLoad(){
count++
console.log(count);
return new Promise((resolve) => {
if(count >= 5){
console.log('Entered if statement and should resolve the promise')
resolve();
}
});
}
async function initialize(){
await onLoad();
count = 0;
console.log('Promise Resolved Successfully!')
}
setTimeout(() => onLoad(), 2000);
setTimeout(() => onLoad(), 4000);
setTimeout(() => onLoad(), 5000);
setTimeout(() => onLoad(), 6000);
setTimeout(() => onLoad(), 7000);
setTimeout(() => initialize(), 3000);
The objective is to resolve the promise after the onLoad()
function is called 5 times.
Otherwise, it should delay the resolution until then regardless of when the initialize
function is invoked...
Note: I'm confused because even though the code reaches the if statement, the promise still doesn't get resolved!?
Note 2: Adding to the confusion, the code works here but fails in the Chrome console and on JSFiddle?????