SlideShare a Scribd company logo
Модель совпадения и цикл
событий.
Асинхронное выполнение, функции
как колбэки, Promise
Masters Academy, 2018
Call stack, event loop and async programming
Call stack, event loop and async programming
Call stack, event loop and async programming
1. Стэк (stack) контекстов
выполнения функций
программы
2. Куча (heap) -
неструктурированная
область памяти, для
хранения объектов
3. Очередь событий (queue) -
список событий, подлежащих
обработке вследствие
выполнения асинхронных
операций
and more...
function foo(x) {
return 5 * x;
}
function bar(y) {
return foo(y) - 3;
}
function baz(z) {
return bar(z) + 7;
}
baz(15);
“First in - last out” principle
function foo(x) {
return 5 * x;
}
function bar(y) {
return foo(y) - 3;
}
function baz(z) {
return bar(z) + 7;
}
baz(15);
function foo(x) {
return 5 * x;
}
function bar(y) {
return foo(y) - 3;
}
function baz(z) {
return bar(z) + 7;
}
baz(15);
function foo(x) {
return 5 * x;
}
function bar(y) {
return foo(y) - 3;
}
function baz(z) {
return bar(z) + 7;
}
baz(15);
function foo(x) {
return 5 * x;
}
function bar(y) {
return foo(y) - 3;
}
function baz(z) {
return bar(z) + 7;
}
baz(15);
function foo(x) {
return 5 * x;
}
function bar(y) {
return foo(y) - 3;
}
function baz(z) {
return bar(z) + 7;
}
baz(15);
function foo(x) {
return 5 * x;
}
function bar(y) {
return foo(y) - 3;
}
function baz(z) {
return bar(z) + 7;
}
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
setTimeout(function() {
console.log(‘timeout 500 complete!’);
}, 500);
function foo(x) { return 5 * x; }
setTimeout(function() {
console.log(‘timeout 0 complete!’);
}, 0);
function baz(z) { console.log(foo(z) + 7) }
baz(15);
Output:
// 82
// timeout 0 complete
// timeout 500 complete
Callbacks
setTimeout(() => {
console.log(‘Hello World!’)
}, 1000);
ajax(‘http://someurl.com’, ‘GET’, data => console.log(data)) // ajax in some http lib
element.addEventListener(‘click’, evt => console.log(‘element clicked!!!’))
Callback Hell
button.addEventListener(‘click’, (evt) => {
ajax(`http://authorize.com/${evt.target.id}`, ‘GET’, res => {
ajax(`http://someapi.com/${res}`, ‘GET’, data => {
setTimeout(() => {
console.log(`finally some data: ${data}`)
}, 500)
})
})
});
Call stack, event loop and async programming
Inversion of control /
Инверсия контроля
Promise
const promise = new Promise((resolve, reject) => {
ajax(‘http://sample.com’, ‘GET’, done => resolve(done), err => reject(err))
})
promise
.then(res => console.log(res))
.catch(err => console.log(‘Error occurred!’))
.finally(() => console.log(‘Hello from resolved/rejected promise!!’))
Promise features
1. No inversion of control, you get the future value
2. Immutable after resolve/reject
3. Completes only once (resolve/reject)
4. Chainable, always returns a Promise instance
5. Lighter syntax
6. Utilizes ES6 Jobs (acts like async microtask, not task)
7. Promise.all, Promise.race and more
8. Cannot be cancelled
Promise Chaining
function createRequest(url) {
return new Promise((resolve, reject) => {
ajax(url, resolve, reject); // assume ajax is some http library
})
}
const promise = createRequest(‘http://auth.com’);
promise.then(createRequest).then(createRequest).catch(console.log)
Handy to use
Promise.all // resolves when all promises are resolved
Promise.race // resolves when one of promises is resolved
fetch // A modern replacement for XMLHttpRequest
async functions
async function authorizeUser(user, pass) {
const authUrl = await createRequest(`http://auth.com/${user}/${pass}`);
const userData = await createRequest(authUrl);
return userData;
}
authorizeUser(‘Jon Doe’, ‘very_secure_password’)
.then(console.log).catch(console.log);
Good resources
1. https://www.youtube.com/watch?v=8aGhZQkoFbQ nice video about call stack
and event loop
1. https://medium.com/front-end-hacking/callbacks-promises-and-async-await-
ad4756e01d90 callback, Promise, async/await concepts
1. https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
tasks vs microtasks in event loop
Homework
Create a function logNumbers() which accepts one argument of type ‘number’.
After one second log into console this number + 10.
After two seconds log into console previous step result * 3.
After three seconds log into console previous step result - 20.
Provide callback, Promise and async/await based solution.
Homework ** (only if you get bored with first one)
fetch() is cool for HTTP requests. It’s Promise-based and has lots of options. But
as Promise resolves/rejects only once and stays immutable, we cannot use it for
reporting file upload progress purposes (PUT). Create a function which would
provide a possible solution for this.
Hint: this function will not use fetch()

More Related Content

What's hot (20)

Node.js flow control
Node.js flow controlNode.js flow control
Node.js flow control
Simon Su
 
The Ring programming language version 1.5.2 book - Part 75 of 181
The Ring programming language version 1.5.2 book - Part 75 of 181The Ring programming language version 1.5.2 book - Part 75 of 181
The Ring programming language version 1.5.2 book - Part 75 of 181
Mahmoud Samir Fayed
 
Extreme JavaScript Performance
Extreme JavaScript PerformanceExtreme JavaScript Performance
Extreme JavaScript Performance
Thomas Fuchs
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Mani Singh
 
The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180
Mahmoud Samir Fayed
 
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
Péhápkaři
 
What is row level isolation on cassandra
What is row level isolation on cassandraWhat is row level isolation on cassandra
What is row level isolation on cassandra
Kazutaka Tomita
 
Debugging JavaScript with Chrome
Debugging JavaScript with ChromeDebugging JavaScript with Chrome
Debugging JavaScript with Chrome
Igor Zalutsky
 
Zone.js 2017
Zone.js 2017Zone.js 2017
Zone.js 2017
Jia Li
 
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays
 
99 líneas que lo simplifican todo( sin animar)
99 líneas que lo simplifican todo( sin animar)99 líneas que lo simplifican todo( sin animar)
99 líneas que lo simplifican todo( sin animar)
nosina
 
Promise is a Promise
Promise is a PromisePromise is a Promise
Promise is a Promise
Mateusz Bryła
 
Universal JavaScript
Universal JavaScriptUniversal JavaScript
Universal JavaScript
名辰 洪
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
Noritada Shimizu
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
Christoffer Noring
 
RxJS 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
C4Media
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
Kyung Yeol Kim
 
サイ本 文
サイ本 文サイ本 文
サイ本 文
Takashi Takizawa
 
Ejercicios
EjerciciosEjercicios
Ejercicios
leonharo
 
Gevent rabbit rpc
Gevent rabbit rpcGevent rabbit rpc
Gevent rabbit rpc
Aleksandr Mokrov
 
Node.js flow control
Node.js flow controlNode.js flow control
Node.js flow control
Simon Su
 
The Ring programming language version 1.5.2 book - Part 75 of 181
The Ring programming language version 1.5.2 book - Part 75 of 181The Ring programming language version 1.5.2 book - Part 75 of 181
The Ring programming language version 1.5.2 book - Part 75 of 181
Mahmoud Samir Fayed
 
Extreme JavaScript Performance
Extreme JavaScript PerformanceExtreme JavaScript Performance
Extreme JavaScript Performance
Thomas Fuchs
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Mani Singh
 
The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180The Ring programming language version 1.5.1 book - Part 65 of 180
The Ring programming language version 1.5.1 book - Part 65 of 180
Mahmoud Samir Fayed
 
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
Jakub Kulhán - ReactPHP + Symfony = PROFIT (1. sraz přátel Symfony v Praze)
Péhápkaři
 
What is row level isolation on cassandra
What is row level isolation on cassandraWhat is row level isolation on cassandra
What is row level isolation on cassandra
Kazutaka Tomita
 
Debugging JavaScript with Chrome
Debugging JavaScript with ChromeDebugging JavaScript with Chrome
Debugging JavaScript with Chrome
Igor Zalutsky
 
Zone.js 2017
Zone.js 2017Zone.js 2017
Zone.js 2017
Jia Li
 
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays
 
99 líneas que lo simplifican todo( sin animar)
99 líneas que lo simplifican todo( sin animar)99 líneas que lo simplifican todo( sin animar)
99 líneas que lo simplifican todo( sin animar)
nosina
 
Universal JavaScript
Universal JavaScriptUniversal JavaScript
Universal JavaScript
名辰 洪
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
Noritada Shimizu
 
RxJS 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
C4Media
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
Kyung Yeol Kim
 
Ejercicios
EjerciciosEjercicios
Ejercicios
leonharo
 

Similar to Call stack, event loop and async programming (20)

Asynchronous programming with java script and node.js
Asynchronous programming with java script and node.jsAsynchronous programming with java script and node.js
Asynchronous programming with java script and node.js
Timur Shemsedinov
 
JS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsJS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js Antipatterns
Timur Shemsedinov
 
A promise is a Promise
A promise is a PromiseA promise is a Promise
A promise is a Promise
Mateusz Bryła
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
The Mystery of Event Loop in JavaScript
The Mystery of Event Loop in JavaScriptThe Mystery of Event Loop in JavaScript
The Mystery of Event Loop in JavaScript
Trình Đức Trần
 
Event driven javascript
Event driven javascriptEvent driven javascript
Event driven javascript
Francesca1980
 
Event driven javascript
Event driven javascriptEvent driven javascript
Event driven javascript
Francesca1980
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
Joseph Chiang
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo
 
Deep Dive into Zone.JS
Deep Dive into Zone.JSDeep Dive into Zone.JS
Deep Dive into Zone.JS
Ilia Idakiev
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
The Software House
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
Saša Tatar
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
Alexe Bogdan
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, code
Kamil Witecki
 
Event Driven Javascript
Event Driven JavascriptEvent Driven Javascript
Event Driven Javascript
Federico Galassi
 
Asynchronous programming and mutlithreading
Asynchronous programming and mutlithreadingAsynchronous programming and mutlithreading
Asynchronous programming and mutlithreading
Timur Shemsedinov
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous calls
Huy Hoàng Phạm
 
Asynchronous programming with java script and node.js
Asynchronous programming with java script and node.jsAsynchronous programming with java script and node.js
Asynchronous programming with java script and node.js
Timur Shemsedinov
 
JS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsJS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js Antipatterns
Timur Shemsedinov
 
A promise is a Promise
A promise is a PromiseA promise is a Promise
A promise is a Promise
Mateusz Bryła
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
The Mystery of Event Loop in JavaScript
The Mystery of Event Loop in JavaScriptThe Mystery of Event Loop in JavaScript
The Mystery of Event Loop in JavaScript
Trình Đức Trần
 
Event driven javascript
Event driven javascriptEvent driven javascript
Event driven javascript
Francesca1980
 
Event driven javascript
Event driven javascriptEvent driven javascript
Event driven javascript
Francesca1980
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo
 
Deep Dive into Zone.JS
Deep Dive into Zone.JSDeep Dive into Zone.JS
Deep Dive into Zone.JS
Ilia Idakiev
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
The Software House
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
Saša Tatar
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
Alexe Bogdan
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, code
Kamil Witecki
 
Asynchronous programming and mutlithreading
Asynchronous programming and mutlithreadingAsynchronous programming and mutlithreading
Asynchronous programming and mutlithreading
Timur Shemsedinov
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous calls
Huy Hoàng Phạm
 
Ad

More from Masters Academy (20)

Ruby Exceptions
Ruby ExceptionsRuby Exceptions
Ruby Exceptions
Masters Academy
 
API
APIAPI
API
Masters Academy
 
Basic Net technologies
Basic Net technologiesBasic Net technologies
Basic Net technologies
Masters Academy
 
Databases
DatabasesDatabases
Databases
Masters Academy
 
Environment
EnvironmentEnvironment
Environment
Masters Academy
 
Frontend
FrontendFrontend
Frontend
Masters Academy
 
Development Methodologies
Development MethodologiesDevelopment Methodologies
Development Methodologies
Masters Academy
 
Object-Oriented Programming
Object-Oriented ProgrammingObject-Oriented Programming
Object-Oriented Programming
Masters Academy
 
Testing
TestingTesting
Testing
Masters Academy
 
Processing
ProcessingProcessing
Processing
Masters Academy
 
Serialization
SerializationSerialization
Serialization
Masters Academy
 
Serverless
ServerlessServerless
Serverless
Masters Academy
 
Data Types
Data TypesData Types
Data Types
Masters Academy
 
How to be up todate
How to be up todateHow to be up todate
How to be up todate
Masters Academy
 
Html, css, js
Html, css, jsHtml, css, js
Html, css, js
Masters Academy
 
Server architecture
Server architectureServer architecture
Server architecture
Masters Academy
 
Serialization
SerializationSerialization
Serialization
Masters Academy
 
Data types
Data typesData types
Data types
Masters Academy
 
Net Technologies
Net TechnologiesNet Technologies
Net Technologies
Masters Academy
 
Net Technologies
Net TechnologiesNet Technologies
Net Technologies
Masters Academy
 
Ad

Recently uploaded (20)

WRITTEN THEME ROUND- OPEN GENERAL QUIZ.pptx
WRITTEN THEME ROUND- OPEN GENERAL QUIZ.pptxWRITTEN THEME ROUND- OPEN GENERAL QUIZ.pptx
WRITTEN THEME ROUND- OPEN GENERAL QUIZ.pptx
Sourav Kr Podder
 
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGYHUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
DHARMENDRA SAHU
 
Pharmaceutical_Incompatibilities.pptx
Pharmaceutical_Incompatibilities.pptxPharmaceutical_Incompatibilities.pptx
Pharmaceutical_Incompatibilities.pptx
Shantanu Ranjan
 
Fatman Book HD Pdf by aayush songare.pdf
Fatman Book  HD Pdf by aayush songare.pdfFatman Book  HD Pdf by aayush songare.pdf
Fatman Book HD Pdf by aayush songare.pdf
Aayush Songare
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
A Brief Introduction About Jack Lutkus
A Brief Introduction About  Jack  LutkusA Brief Introduction About  Jack  Lutkus
A Brief Introduction About Jack Lutkus
Jack Lutkus
 
Uterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managmentUterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managment
Ritu480198
 
How to Configure Add to Cart in Odoo 18 Website
How to Configure Add to Cart in Odoo 18 WebsiteHow to Configure Add to Cart in Odoo 18 Website
How to Configure Add to Cart in Odoo 18 Website
Celine George
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in IndiaSmart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
fincrifcontent
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
RVSPSOA
 
la storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglesela storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglese
LetiziaLucente
 
Freckle Project April 2025 Survey and report May 2025.pptx
Freckle Project April 2025 Survey and report May 2025.pptxFreckle Project April 2025 Survey and report May 2025.pptx
Freckle Project April 2025 Survey and report May 2025.pptx
EveryLibrary
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
Pragya Champion's Chalice 2025 Set , General Quiz
Pragya Champion's Chalice 2025 Set , General QuizPragya Champion's Chalice 2025 Set , General Quiz
Pragya Champion's Chalice 2025 Set , General Quiz
Pragya - UEM Kolkata Quiz Club
 
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad LevelLDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDM & Mia eStudios
 
Diana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda - A Wauconda-Based EducatorDiana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda
 
WRITTEN THEME ROUND- OPEN GENERAL QUIZ.pptx
WRITTEN THEME ROUND- OPEN GENERAL QUIZ.pptxWRITTEN THEME ROUND- OPEN GENERAL QUIZ.pptx
WRITTEN THEME ROUND- OPEN GENERAL QUIZ.pptx
Sourav Kr Podder
 
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGYHUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
HUMAN SKELETAL SYSTEM ANATAMY AND PHYSIOLOGY
DHARMENDRA SAHU
 
Pharmaceutical_Incompatibilities.pptx
Pharmaceutical_Incompatibilities.pptxPharmaceutical_Incompatibilities.pptx
Pharmaceutical_Incompatibilities.pptx
Shantanu Ranjan
 
Fatman Book HD Pdf by aayush songare.pdf
Fatman Book  HD Pdf by aayush songare.pdfFatman Book  HD Pdf by aayush songare.pdf
Fatman Book HD Pdf by aayush songare.pdf
Aayush Songare
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
A Brief Introduction About Jack Lutkus
A Brief Introduction About  Jack  LutkusA Brief Introduction About  Jack  Lutkus
A Brief Introduction About Jack Lutkus
Jack Lutkus
 
Uterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managmentUterine Prolapse, causes type and classification,its managment
Uterine Prolapse, causes type and classification,its managment
Ritu480198
 
How to Configure Add to Cart in Odoo 18 Website
How to Configure Add to Cart in Odoo 18 WebsiteHow to Configure Add to Cart in Odoo 18 Website
How to Configure Add to Cart in Odoo 18 Website
Celine George
 
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in IndiaSmart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
fincrifcontent
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...
RVSPSOA
 
la storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglesela storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglese
LetiziaLucente
 
Freckle Project April 2025 Survey and report May 2025.pptx
Freckle Project April 2025 Survey and report May 2025.pptxFreckle Project April 2025 Survey and report May 2025.pptx
Freckle Project April 2025 Survey and report May 2025.pptx
EveryLibrary
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad LevelLDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDM & Mia eStudios
 
Diana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda - A Wauconda-Based EducatorDiana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda
 

Call stack, event loop and async programming

  • 1. Модель совпадения и цикл событий. Асинхронное выполнение, функции как колбэки, Promise Masters Academy, 2018
  • 5. 1. Стэк (stack) контекстов выполнения функций программы 2. Куча (heap) - неструктурированная область памяти, для хранения объектов 3. Очередь событий (queue) - список событий, подлежащих обработке вследствие выполнения асинхронных операций
  • 7. function foo(x) { return 5 * x; } function bar(y) { return foo(y) - 3; } function baz(z) { return bar(z) + 7; } baz(15); “First in - last out” principle
  • 8. function foo(x) { return 5 * x; } function bar(y) { return foo(y) - 3; } function baz(z) { return bar(z) + 7; } baz(15);
  • 9. function foo(x) { return 5 * x; } function bar(y) { return foo(y) - 3; } function baz(z) { return bar(z) + 7; } baz(15);
  • 10. function foo(x) { return 5 * x; } function bar(y) { return foo(y) - 3; } function baz(z) { return bar(z) + 7; } baz(15);
  • 11. function foo(x) { return 5 * x; } function bar(y) { return foo(y) - 3; } function baz(z) { return bar(z) + 7; } baz(15);
  • 12. function foo(x) { return 5 * x; } function bar(y) { return foo(y) - 3; } function baz(z) { return bar(z) + 7; } baz(15);
  • 13. function foo(x) { return 5 * x; } function bar(y) { return foo(y) - 3; } function baz(z) { return bar(z) + 7; } baz(15);
  • 14. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 15. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 16. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 17. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 18. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 19. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 20. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 21. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 22. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 23. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 24. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 25. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 26. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 27. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 28. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15);
  • 29. setTimeout(function() { console.log(‘timeout 500 complete!’); }, 500); function foo(x) { return 5 * x; } setTimeout(function() { console.log(‘timeout 0 complete!’); }, 0); function baz(z) { console.log(foo(z) + 7) } baz(15); Output: // 82 // timeout 0 complete // timeout 500 complete
  • 30. Callbacks setTimeout(() => { console.log(‘Hello World!’) }, 1000); ajax(‘http://someurl.com’, ‘GET’, data => console.log(data)) // ajax in some http lib element.addEventListener(‘click’, evt => console.log(‘element clicked!!!’))
  • 31. Callback Hell button.addEventListener(‘click’, (evt) => { ajax(`http://authorize.com/${evt.target.id}`, ‘GET’, res => { ajax(`http://someapi.com/${res}`, ‘GET’, data => { setTimeout(() => { console.log(`finally some data: ${data}`) }, 500) }) }) });
  • 33. Inversion of control / Инверсия контроля
  • 34. Promise const promise = new Promise((resolve, reject) => { ajax(‘http://sample.com’, ‘GET’, done => resolve(done), err => reject(err)) }) promise .then(res => console.log(res)) .catch(err => console.log(‘Error occurred!’)) .finally(() => console.log(‘Hello from resolved/rejected promise!!’))
  • 35. Promise features 1. No inversion of control, you get the future value 2. Immutable after resolve/reject 3. Completes only once (resolve/reject) 4. Chainable, always returns a Promise instance 5. Lighter syntax 6. Utilizes ES6 Jobs (acts like async microtask, not task) 7. Promise.all, Promise.race and more 8. Cannot be cancelled
  • 36. Promise Chaining function createRequest(url) { return new Promise((resolve, reject) => { ajax(url, resolve, reject); // assume ajax is some http library }) } const promise = createRequest(‘http://auth.com’); promise.then(createRequest).then(createRequest).catch(console.log)
  • 37. Handy to use Promise.all // resolves when all promises are resolved Promise.race // resolves when one of promises is resolved fetch // A modern replacement for XMLHttpRequest
  • 38. async functions async function authorizeUser(user, pass) { const authUrl = await createRequest(`http://auth.com/${user}/${pass}`); const userData = await createRequest(authUrl); return userData; } authorizeUser(‘Jon Doe’, ‘very_secure_password’) .then(console.log).catch(console.log);
  • 39. Good resources 1. https://www.youtube.com/watch?v=8aGhZQkoFbQ nice video about call stack and event loop 1. https://medium.com/front-end-hacking/callbacks-promises-and-async-await- ad4756e01d90 callback, Promise, async/await concepts 1. https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/ tasks vs microtasks in event loop
  • 40. Homework Create a function logNumbers() which accepts one argument of type ‘number’. After one second log into console this number + 10. After two seconds log into console previous step result * 3. After three seconds log into console previous step result - 20. Provide callback, Promise and async/await based solution.
  • 41. Homework ** (only if you get bored with first one) fetch() is cool for HTTP requests. It’s Promise-based and has lots of options. But as Promise resolves/rejects only once and stays immutable, we cannot use it for reporting file upload progress purposes (PUT). Create a function which would provide a possible solution for this. Hint: this function will not use fetch()