I have this piece of code that really confuses me, so I will try to paste it here and write down by words how I think it is executed, it probably won't be correct so you can correct me.
const wait = function(seconds) {
return new Promise(function(resolve) {
setTimeout(resolve, seconds * 1000);
});
};
wait(1)
.then(() => {
console.log(`1 second passed`);
return wait(1);
})
.then(() => {
console.log(`2 second passed`);
return wait(1);
})
.then(() => {
console.log(`3 second passed`);
return wait(1);
})
.then(() => {
console.log(`4 second passed`);
return wait(1);
})
.then(() => console.log(`5 second passed`));
So the part that confuses me is setting 'resolve' as a callback inside the setTimeout function, I will try to write step by step and you can correct me if it is wrong.
- Step 1: We are calling wait function and passing 1 as a seconds argument
- Step 2: Inside the function, we are creating a new Promise where we specified what happens only if the promise is settled(fulfilled), we don't care about rejection.
- Step 3: Inside the promise constructor, we have setTimeout function with resolve as a callback which will be called after a 1-second pass.
- Step 4: A second has passed, now our promise is fulfilled, the
thenmethod is fired. Since our 'resolve' is empty we can't use thethenmethod's argument RIGHT? But still, then the method is fired after one second so we can use that to our advantage to log to the console that "1 second passed". - Step 5: We are returning new promises so we can chain methods.
