I am learning promise recently and when I am play about .then I found I could not explain what i found in this code for myself... I know we should avoid from using nested then, because one of the advantages of .then is no callback hell any more. But in this case, i just want to check the order of then process, and i was stuck.. .
let p2 = Promise.resolve('nested 1');
Promise.resolve ('1')
.then(function(result) {
console.log(result);
p2.then((result1)=> {
console.log(result1);
return 'nested 2'
})
.then((result2) => {
console.log(result2);
return 'nested 3'
})
.then((result3)=> {
console.log(result3);
})
})
.then(() => { console.log("2"); })
.then(() => { console.log("3"); })
.then(() => { console.log("4"); })
.catch(function(err) {
console.log(err);
});
setTimeout(()=>{console.log("5")}, 3)
console.log("6")
the output is:
6 // current task
1
nested 1
2
nested 2
3
nested 3
4
5 //next task because of setTimout
What i can not understand is the handler order from '1' to '4'. I know all of them are microTasks after '6', but why are not the order of the microtasks as '1' => '2' =>'3' => '4'=> 'nested 1'=> 'nested 2' => 'nested 3'? I use Chrome.
Can anyone kindly give me some hints? Thank you very much.