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

PDF
ESCMAScript 6: Get Ready For The Future. Now
Krzysztof Szafranek
 
PPS
Ecma script 5
Alexander Tarasyuk
 
PDF
RxJS - 封裝程式的藝術
名辰 洪
 
PDF
如何「畫圖」寫測試 - RxJS Marble Test
名辰 洪
 
PPTX
AngularJS Testing
Eyal Vardi
 
PDF
Rich and Snappy Apps (No Scaling Required)
Thomas Fuchs
 
PDF
You will learn RxJS in 2017
名辰 洪
 
PDF
The Ring programming language version 1.6 book - Part 71 of 189
Mahmoud Samir Fayed
 
ESCMAScript 6: Get Ready For The Future. Now
Krzysztof Szafranek
 
Ecma script 5
Alexander Tarasyuk
 
RxJS - 封裝程式的藝術
名辰 洪
 
如何「畫圖」寫測試 - RxJS Marble Test
名辰 洪
 
AngularJS Testing
Eyal Vardi
 
Rich and Snappy Apps (No Scaling Required)
Thomas Fuchs
 
You will learn RxJS in 2017
名辰 洪
 
The Ring programming language version 1.6 book - Part 71 of 189
Mahmoud Samir Fayed
 

What's hot (20)

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

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

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

More from Masters Academy (20)

PPTX
Ruby Exceptions
Masters Academy
 
PPTX
Basic Net technologies
Masters Academy
 
PPTX
Databases
Masters Academy
 
PPTX
Environment
Masters Academy
 
PPTX
Frontend
Masters Academy
 
PPTX
Development Methodologies
Masters Academy
 
PPTX
Object-Oriented Programming
Masters Academy
 
PPTX
Testing
Masters Academy
 
PPTX
Processing
Masters Academy
 
PPTX
Serialization
Masters Academy
 
PPTX
Serverless
Masters Academy
 
PPTX
Data Types
Masters Academy
 
PPTX
How to be up todate
Masters Academy
 
PPTX
Html, css, js
Masters Academy
 
PPTX
Server architecture
Masters Academy
 
PPTX
Serialization
Masters Academy
 
PPTX
Data types
Masters Academy
 
PPTX
Net Technologies
Masters Academy
 
PPTX
Net Technologies
Masters Academy
 
Ruby Exceptions
Masters Academy
 
Basic Net technologies
Masters Academy
 
Databases
Masters Academy
 
Environment
Masters Academy
 
Frontend
Masters Academy
 
Development Methodologies
Masters Academy
 
Object-Oriented Programming
Masters Academy
 
Processing
Masters Academy
 
Serialization
Masters Academy
 
Serverless
Masters Academy
 
Data Types
Masters Academy
 
How to be up todate
Masters Academy
 
Html, css, js
Masters Academy
 
Server architecture
Masters Academy
 
Serialization
Masters Academy
 
Data types
Masters Academy
 
Net Technologies
Masters Academy
 
Net Technologies
Masters Academy
 

Recently uploaded (20)

PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
Introduction and Scope of Bichemistry.pptx
shantiyogi
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
MariellaTBesana
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PDF
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
Introduction and Scope of Bichemistry.pptx
shantiyogi
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Week 4 Term 3 Study Techniques revisited.pptx
mansk2
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
MariellaTBesana
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Electricity-Magnetic-and-Heating-Effects 4th Chapter/8th-science-curiosity.pd...
Sandeep Swamy
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
Landforms and landscapes data surprise preview
jpinnuck
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 

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