0

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.

ss m
  • 1
  • it's really hard to explain but because the first .then doesn't return a promise,you end up with p2.then on the MicroTaskQueue, and then the second first level `.then`, and then when `p2.then` is done, the `result2` then gets put on the MTQ, and the second first level .then is processed, which puts the next .then in the MTQ ... and so forth ... if you `return p2.then((result1)=> {` ... then the output is `'1' => 'nested 1'=> 'nested 2' => 'nested 3' => '2' =>'3' => '4'` - but you'll never get what you expect - also the fact that you use Chrome is irrelevant :p – Jaromanda X Oct 03 '18 at 11:12
  • 1
    You should not bother about the ordering of individual callbacks. Consider them chaotic if you want. Your promise chains only specify "2 after 1", "3 after 2", "4 after 3", "1 after 6", "5 after 6", "nested 1 after 1", "nested 2 after nested 1", "nested 3 after nested 2". *Any* order that satisfies these constraints should be considered possible. If you want a different order, be explicit about it. – Bergi Oct 03 '18 at 12:56

0 Answers0