When we chain a Promise's using chain, and the Promise is returned by then, so how code that isn't part of the then chain runs before the all chain was finished? How does the code jump over then calls? Shouldn't all then calls performed before running the "console.log" line of code?
Here is the code:
Promise.resolve('333')
.then((res)=>{console.log(res);return new Promise((resolve,reject)=> {setTimeout(function(){console.log('Timeout');resolve(1);},10000);console.log('Something');})})
.then((res)=>{console.log(res);return new Promise((resolve,reject)=> {console.log('Something');resolve(2);})})
.then((res)=>{console.log(res);return new Promise((resolve,reject)=> {console.log('Something');resolve(3);})})
.then((res)=>{console.log(res);return new Promise((resolve,reject)=> {console.log('Something');resolve(4);})})
console.log("When?")
In the output "When?" is being printed first.. Now i can't understand how is it possible since the callback in the first then will run only in about 10 seconds and only after that, the callback will return a Promise that will run the second then? Maybe i don't understand how the callback of then "goes with" the then function. I thought that then implementation looks a little bit like:
then(callback){
let value= callback();
if(value is promise){
return value;
}
return Promise.resolve(value)
}