SlideShare une entreprise Scribd logo
1  sur  41
Модель совпадения и цикл
событий.
Асинхронное выполнение, функции
как колбэки, Promise
Masters Academy, 2018
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)
})
})
});
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()

Contenu connexe

Tendances

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
 
Ejercicios
EjerciciosEjercicios
Ejercicios
leonharo
 

Tendances (20)

Node.js flow control
Node.js flow controlNode.js flow control
Node.js flow control
 
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
 
Extreme JavaScript Performance
Extreme JavaScript PerformanceExtreme JavaScript Performance
Extreme JavaScript Performance
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
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
 
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)
 
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
 
Debugging JavaScript with Chrome
Debugging JavaScript with ChromeDebugging JavaScript with Chrome
Debugging JavaScript with Chrome
 
Zone.js 2017
Zone.js 2017Zone.js 2017
Zone.js 2017
 
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
 
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)
 
Promise is a Promise
Promise is a PromisePromise is a Promise
Promise is a Promise
 
Universal JavaScript
Universal JavaScriptUniversal JavaScript
Universal JavaScript
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
RxJS 5 in Depth
RxJS 5 in DepthRxJS 5 in Depth
RxJS 5 in Depth
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
サイ本 文
サイ本 文サイ本 文
サイ本 文
 
Ejercicios
EjerciciosEjercicios
Ejercicios
 
Gevent rabbit rpc
Gevent rabbit rpcGevent rabbit rpc
Gevent rabbit rpc
 

Similaire à Call stack, event loop and async programming

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
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
Takayuki Goto
 

Similaire à 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
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
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
 
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...
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 

Plus de Masters Academy

Plus de Masters Academy (20)

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

Dernier

Dernier (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

Call stack, event loop and async programming

  • 1. Модель совпадения и цикл событий. Асинхронное выполнение, функции как колбэки, Promise Masters Academy, 2018
  • 2.
  • 3.
  • 4.
  • 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) }) }) });
  • 32.
  • 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()