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()
Ad

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)

FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
Justin Alexander
 
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
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
Bruno Scopelliti
 
ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?
장현 한
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
Alexe Bogdan
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
Luis Vendrame
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
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
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
James Ford
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
Raimonds Simanovskis
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
Felix Geisendörfer
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
Takayuki Goto
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
Piotr Pelczar
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
monikagupta18jan
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
RameshNair6
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
Sebastiano Armeli
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
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
 
ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?
장현 한
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
Alexe Bogdan
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
Luis Vendrame
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
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
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
Raimonds Simanovskis
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
Takayuki Goto
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
Piotr Pelczar
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
RameshNair6
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
Sebastiano Armeli
 
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)

The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 

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()