On exploring Promise 1: thoughts about async and event loop model

Image for post
Image for post
photo by Xullnn

1 From setTimeout to Promise

Image for post
Image for post

2 A simple understanding of “async”

2.1 A feeling about async

| — — — — — — — boil eggs — — — — — — — |
|- heat potato -|
| — — heat water — -|
|- brew coffee -|

2.2 an oversimplified view: async goes after sync

setTimeout(() => {
console.log(“I am the first line.”);
}, 0);
// this line is only added for increasing the time consumption in between
for(let i = 0; i < 1000000000; i += 1 ) {};
console.log(“I am the last line.”);
Promise.resolve(“”).then(() => console.log(“I am the first line.”)); // 1for(let i = 0; i < 1000000000; i += 1 ) {}; // 2console.log(“I am the last line.”); // this always gets printed out first // 3

2.3 why the separation of sync and async makes sense

Promise.resolve(“”).then(() => console.log(“I am the first line.”)); // 1// we can also do Promise.resolve(“”).then(() => for(let i = 0; i < 1000000000; i += 1 ) {});
setTimeout(() => { for(let i = 0; i < 1000000000; i += 1 ) {}}, 0); // 2
console.log(“I am the last line.”); // this always gets printed out first // 3

2.4 to be sync or to be async

3 Mental model of Event Loop — the mechanism to coordinate sync and async tasks

3.1 a feel about event loop

3.2 A demonstration about how event loop operates in browser

3.3 Components of event loop

3.4 run, event loop

setTimeout(() => { console.log("I am the first line.") }, 0); // 1for(let i = 0; i < 1000000000; i += 1 ) {}; // 2console.log("I am the last line."); // 3
Image for post
Image for post

3.5 From model to implementation

4 Summary

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store