javascript Promise excution order -
promise.resolve() .then(() => console.log(2)) .then(() => console.log(3)); promise.resolve() .then(() => console.log(4)) .then(() => console.log(5)); console.log(1);
why above code snippet result 1 2 4 3 5
instead of 1 2 3 4 5
.
what execution order?
it runs in order because that's order callbacks entered callback queue.
lets follow through code does:
promise.resolve() .then(() => console.log(2)) .then(() => console.log(3)); promise.resolve() .then(() => console.log(4)) .then(() => console.log(5)); console.log(1);
first, main code ran, 2 promises created , resolved, , 2 callbacks added callback queue; callbacks 2 , 4. queue [2,4]. console.log(1) happens , function ends.
now function done, next callback in callback queue runs, logging 2, pushes new callback callback queue, callback 3. queue [4,3].
next, callback 4 runs , logs 4, , pushes callback 5 queue. queue [3,5]
next, callbacks 3 , 5 each run in order, bringing queue [].
if of functions asynchronous, order have changed drastically based on how long each took complete.
Comments
Post a Comment