When you run this code
Promise.resolve(console.log('resolved'))
.then(pass => setTimeout((pass) => console.log(`1 then pass=${pass}`), 1000, pass))
.then(pass => setTimeout((pass) => console.log(`2 then pass=${pass}`), 1000, pass))
.then(pass => setTimeout((pass) => console.log(`3 then pass=${pass}`), 1000, pass))
.then(pass => setTimeout((pass) => console.log(`4 then pass=${pass}`), 1000, pass))
.then(pass => console.log(`5 then pass=${pass}`))
.then(pass => console.log(`6 then pass=${pass}`))
you get this in console
resolved
5 then pass=4
6 then pass=undefined
1 then pass=undefined
2 then pass=1
3 then pass=2
4 then pass=3
So the question is where this pass variable gets it's value? Where it is stored as window.pass == undefined? Why it increment? Why it finaly gets undefined as we stop using setTimeout?
setTimeout
returns a TimerID, so that's the value being passed around.
1
and 6
are the results of console.log
calls which return undefined
.