SlideShare a Scribd company logo
1 of 25
Download to read offline
Asynchronous JavaScript
Anssi Kinnunen (@anssikin)
Tech friday 22.01.2016
Asynchrony (programming):
“Refers to the occurrence of events independently of the main
program flow”
https://en.wikipedia.org/wiki/Asynchrony_(computer_programming)
JavaScript
● Event loop -based concurrency model
● Almost all I/O is non-blocking
● Single thread, ask runtime to perform operation, provide
callback and move on to other tasks
https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop
http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/
http://www.2ality.com/2014/09/es6-promises-foundations.html
JavaScript runtime
● Contains a message queue
● Each message is associated with a callback function
● $(‘.btn’).click((evt) => { … })
○ Click (external event) causes message to be queued
https://developer.mozilla.
org/en/docs/Web/JavaScript/EventLoop
http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-
http://www.2ality.com/2014/09/es6-promises-foundations.html
http://stackoverflow.com/a/14797071
JavaScript event loop
● Synchronously processes message queue
● Each message is processed completely before others
○ When callback returns, event loop continues
● window.setTimeout(cb, wait)
https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop
http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/
http://www.2ality.com/2014/09/es6-promises-foundations.html
function () {
console.log('this is the start');
window.setTimeout(() => {
console.log('this is a msg from call back');
});
console.log('this is just a message');
window.setTimeout(() => {
console.log('this is a msg from call back1');
}, 0);
console.log('this is the end');
}
JavaScript event loop
● Browser tab is controlled by a single process
● UI, other computations
● Blocking the event queue?
https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop
http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/
http://www.2ality.com/2014/09/es6-promises-foundations.html
Web Workers
● API designed to allow running scripts in background
threads
● Worker has separate message queue, event loop and
memory space, independent from originating thread
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/
// pi_calculator.js
let reportResult = (e) => {
let pi = computePiToSpecifiedDecimals(e.data);
postMessage(pi);
};
onmessage = reportResult;
// main code
let piWorker = new Worker(‘pi_calculator.js’);
let logResult = (e) => {
console.log(`PI: ${e.data}`);
};
piWorker.addEventListener(‘message’, logResult, false);
piWorker.postMessage(100000);
ES6: Promise
Promise
● Represents (‘proxy’) operation that hasn’t completed yet
● Promise is always in one of three states
○ Pending: result has not been computed, yet
○ Fulfilled: result was computed succesfully
○ Rejected: failure occurred during computation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
http://www.2ality.com/2014/10/es6-promises-api.html
Promise
● Promise.all( [ ] ), Promise.race( [ ] )
● Chaining: then() and catch() return promises
○ Promise() -> then() -> then() -> catch()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
http://www.2ality.com/2014/10/es6-promises-api.html
let doHeavyCalculation = (a, b) => {
return new Promise((resolve, reject) => {
console.log('wait 2000ms');
window.setTimeout(() => {
resolve(a + b);
}, 2000);
});
};
doHeavyCalculation(4, 4).then((result) => {
return doHeavyCalculation(result, 2);
}).then((calculatedValue) => {
console.log(`the result is ${calculatedValue}`);
});
http://www.2ality.com/2014/10/es6-promises-api.html
// Node.js style async file reading
fs.readFile(‘config.json’, (error, text) => {
if (error) {
console.error(‘Error while reading config file’);
} else {
try {
let obj = JSON.parse(text);
console.log(JSON.stringify(obj, null, 4));
} catch (e) {
console.error(‘Invalid JSON in file’);
}
}
});
// Same functionality with promises
readFilePromisified(‘config.json’)
.then((text) => {
let obj = JSON.parse(text);
console.log(JSON.stringify(obj, null, 4));
})
.catch((reason) => {
console.error(`An error occurred ${reason}`);
});
ES7: Async/Await
const request = require('request');
function getQuote() {
return new Promise((resolve, reject) => {
let url = 'http://ron-swanson-quotes.herokuapp.com/v2/quotes';
request(url, (error, response, quote) => {
if (error) {
reject(error);
} else {
resolve(quote);
}
});
});
}
async function main() {
try {
let quote = await getQuote();
console.log(quote);
} catch (e) {
console.error(e);
}
}
main();
https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html
AJAX
Asynchronous JavaScript and XML
AJAX
● Group of technologies for async web
○ HTML/CSS, XML/XSLT, DOM
● Data passed is usually JSON
XHR
XMLHttpRequest
let request;
// Old compatibility code, no longer needed.
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === 200) {
console.log(request.responseText);
}
}
request.open('GET', 'http://davidwalsh.name/ajax-endpoint', true);
request.send(null);
https://davidwalsh.name/xmlhttprequest
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
$.get({
url: 'http://davidwalsh.name/ajax-endpoint',
success: function(response) {
console.log(response);
}
});
Fetch API
https://developer.mozilla.org/en/docs/Web/API/Fetch_API
Fetch
● Interface for fetching resources, not finalized yet
● Like XHR, but more powerful
● window.fetch() -> Promise() -> Response
// Chaining for more "advanced" handling
fetch('/some/url').then((response) => {
return //...
}).then((returnedValue) => {
// ...
}).catch((err) => {
// Error :(
});
https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html

More Related Content

What's hot

How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promiseeslam_me
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 
Even more java script best practices
Even more java script best practicesEven more java script best practices
Even more java script best practicesChengHui Weng
 
Intro to JavaScript Testing
Intro to JavaScript TestingIntro to JavaScript Testing
Intro to JavaScript TestingRan Mizrahi
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
Dependency Injection Smells
Dependency Injection SmellsDependency Injection Smells
Dependency Injection SmellsMatthias Noback
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 
Angular Weekend
Angular WeekendAngular Weekend
Angular WeekendTroy Miles
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptYakov Fain
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution ContextJuan Medina
 
Async JavaScript Unit Testing
Async JavaScript Unit TestingAsync JavaScript Unit Testing
Async JavaScript Unit TestingMihail Gaberov
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 

What's hot (20)

JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
 
Even more java script best practices
Even more java script best practicesEven more java script best practices
Even more java script best practices
 
Intro to JavaScript Testing
Intro to JavaScript TestingIntro to JavaScript Testing
Intro to JavaScript Testing
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Dependency Injection Smells
Dependency Injection SmellsDependency Injection Smells
Dependency Injection Smells
 
Callback Function
Callback FunctionCallback Function
Callback Function
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Angular Weekend
Angular WeekendAngular Weekend
Angular Weekend
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
 
Async JavaScript Unit Testing
Async JavaScript Unit TestingAsync JavaScript Unit Testing
Async JavaScript Unit Testing
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 

Similar to Tech friday 22.01.2016

Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
 
Service workers
Service workersService workers
Service workersjungkees
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformLucio Grenzi
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Codemotion
 
手把手教你如何串接 Log 到各種網路服務
手把手教你如何串接 Log 到各種網路服務手把手教你如何串接 Log 到各種網路服務
手把手教你如何串接 Log 到各種網路服務Mu Chun Wang
 
UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)Yoshifumi Kawai
 
Eclipse IoT Talk (Montreal JUG)
Eclipse IoT Talk (Montreal JUG)Eclipse IoT Talk (Montreal JUG)
Eclipse IoT Talk (Montreal JUG)Mike Milinkovich
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxRAHITNATH
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "FDConf
 
CP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDKCP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDKMifeng
 
Persistent mobile JavaScript
Persistent mobile JavaScriptPersistent mobile JavaScript
Persistent mobile JavaScriptYorick Phoenix
 
Where is my cache architectural patterns for caching microservices by example
Where is my cache architectural patterns for caching microservices by exampleWhere is my cache architectural patterns for caching microservices by example
Where is my cache architectural patterns for caching microservices by exampleRafał Leszko
 
Docker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline ExecutionDocker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline ExecutionBrennan Saeta
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
Monitoring Kafka w/ Prometheus
Monitoring Kafka w/ PrometheusMonitoring Kafka w/ Prometheus
Monitoring Kafka w/ Prometheuskawamuray
 
Improving the Accumulo User Experience
 Improving the Accumulo User Experience Improving the Accumulo User Experience
Improving the Accumulo User ExperienceAccumulo Summit
 

Similar to Tech friday 22.01.2016 (20)

Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Service workers
Service workersService workers
Service workers
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
 
手把手教你如何串接 Log 到各種網路服務
手把手教你如何串接 Log 到各種網路服務手把手教你如何串接 Log 到各種網路服務
手把手教你如何串接 Log 到各種網路服務
 
UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)UniRx - Reactive Extensions for Unity(EN)
UniRx - Reactive Extensions for Unity(EN)
 
Sprint 17
Sprint 17Sprint 17
Sprint 17
 
Eclipse IoT Talk (Montreal JUG)
Eclipse IoT Talk (Montreal JUG)Eclipse IoT Talk (Montreal JUG)
Eclipse IoT Talk (Montreal JUG)
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
 
lecture5
lecture5lecture5
lecture5
 
lecture5
lecture5lecture5
lecture5
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "
 
CP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDKCP3108B (Mozilla) Sharing Session on Add-on SDK
CP3108B (Mozilla) Sharing Session on Add-on SDK
 
Persistent mobile JavaScript
Persistent mobile JavaScriptPersistent mobile JavaScript
Persistent mobile JavaScript
 
Where is my cache architectural patterns for caching microservices by example
Where is my cache architectural patterns for caching microservices by exampleWhere is my cache architectural patterns for caching microservices by example
Where is my cache architectural patterns for caching microservices by example
 
Docker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline ExecutionDocker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline Execution
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Monitoring Kafka w/ Prometheus
Monitoring Kafka w/ PrometheusMonitoring Kafka w/ Prometheus
Monitoring Kafka w/ Prometheus
 
Improving the Accumulo User Experience
 Improving the Accumulo User Experience Improving the Accumulo User Experience
Improving the Accumulo User Experience
 

More from Poutapilvi Web Design

Vihree ois kiva - Mitä muuta suunnittelija haluaisi kuulla asiakkaalta
Vihree ois kiva - Mitä muuta suunnittelija haluaisi kuulla asiakkaaltaVihree ois kiva - Mitä muuta suunnittelija haluaisi kuulla asiakkaalta
Vihree ois kiva - Mitä muuta suunnittelija haluaisi kuulla asiakkaaltaPoutapilvi Web Design
 
Verkossa verkon tavalla - teetkö hyvin vai teetkö itse?
Verkossa verkon tavalla - teetkö hyvin vai teetkö itse?Verkossa verkon tavalla - teetkö hyvin vai teetkö itse?
Verkossa verkon tavalla - teetkö hyvin vai teetkö itse?Poutapilvi Web Design
 
Käytännön työkaluilla verkkosivu-uudistuksen alkuun
Käytännön työkaluilla verkkosivu-uudistuksen alkuunKäytännön työkaluilla verkkosivu-uudistuksen alkuun
Käytännön työkaluilla verkkosivu-uudistuksen alkuunPoutapilvi Web Design
 
Käyttöliittymästä kilpailuetua
Käyttöliittymästä kilpailuetuaKäyttöliittymästä kilpailuetua
Käyttöliittymästä kilpailuetuaPoutapilvi Web Design
 
Täydellinen ostaja - yllättävän helppoa
Täydellinen ostaja - yllättävän helppoaTäydellinen ostaja - yllättävän helppoa
Täydellinen ostaja - yllättävän helppoaPoutapilvi Web Design
 
Viestijä asiantuntijana, asiantuntijat viestijöinä
Viestijä asiantuntijana, asiantuntijat viestijöinäViestijä asiantuntijana, asiantuntijat viestijöinä
Viestijä asiantuntijana, asiantuntijat viestijöinäPoutapilvi Web Design
 
Tekeekö verkkopalvelu työnsä - seitsemän kysymystä, joihin sivusi tulisi vastata
Tekeekö verkkopalvelu työnsä - seitsemän kysymystä, joihin sivusi tulisi vastataTekeekö verkkopalvelu työnsä - seitsemän kysymystä, joihin sivusi tulisi vastata
Tekeekö verkkopalvelu työnsä - seitsemän kysymystä, joihin sivusi tulisi vastataPoutapilvi Web Design
 
Johtaja sisällöntuottajana - näin aion onnistua
Johtaja sisällöntuottajana - näin aion onnistuaJohtaja sisällöntuottajana - näin aion onnistua
Johtaja sisällöntuottajana - näin aion onnistuaPoutapilvi Web Design
 
Arvaa selvitä kerro - käyttäjän odotukset verkkopalvelulta
Arvaa selvitä kerro - käyttäjän odotukset verkkopalvelultaArvaa selvitä kerro - käyttäjän odotukset verkkopalvelulta
Arvaa selvitä kerro - käyttäjän odotukset verkkopalvelultaPoutapilvi Web Design
 

More from Poutapilvi Web Design (14)

Vihree ois kiva - Mitä muuta suunnittelija haluaisi kuulla asiakkaalta
Vihree ois kiva - Mitä muuta suunnittelija haluaisi kuulla asiakkaaltaVihree ois kiva - Mitä muuta suunnittelija haluaisi kuulla asiakkaalta
Vihree ois kiva - Mitä muuta suunnittelija haluaisi kuulla asiakkaalta
 
Verkossa verkon tavalla - teetkö hyvin vai teetkö itse?
Verkossa verkon tavalla - teetkö hyvin vai teetkö itse?Verkossa verkon tavalla - teetkö hyvin vai teetkö itse?
Verkossa verkon tavalla - teetkö hyvin vai teetkö itse?
 
Käytännön työkaluilla verkkosivu-uudistuksen alkuun
Käytännön työkaluilla verkkosivu-uudistuksen alkuunKäytännön työkaluilla verkkosivu-uudistuksen alkuun
Käytännön työkaluilla verkkosivu-uudistuksen alkuun
 
Ennakoi ja menesty
Ennakoi ja menestyEnnakoi ja menesty
Ennakoi ja menesty
 
Verkkosisällön ehdoilla
Verkkosisällön ehdoillaVerkkosisällön ehdoilla
Verkkosisällön ehdoilla
 
Käyttöliittymästä kilpailuetua
Käyttöliittymästä kilpailuetuaKäyttöliittymästä kilpailuetua
Käyttöliittymästä kilpailuetua
 
Täydellinen ostaja - yllättävän helppoa
Täydellinen ostaja - yllättävän helppoaTäydellinen ostaja - yllättävän helppoa
Täydellinen ostaja - yllättävän helppoa
 
Someen voi vain mennä
Someen voi vain mennäSomeen voi vain mennä
Someen voi vain mennä
 
Viestijä asiantuntijana, asiantuntijat viestijöinä
Viestijä asiantuntijana, asiantuntijat viestijöinäViestijä asiantuntijana, asiantuntijat viestijöinä
Viestijä asiantuntijana, asiantuntijat viestijöinä
 
Tekeekö verkkopalvelu työnsä - seitsemän kysymystä, joihin sivusi tulisi vastata
Tekeekö verkkopalvelu työnsä - seitsemän kysymystä, joihin sivusi tulisi vastataTekeekö verkkopalvelu työnsä - seitsemän kysymystä, joihin sivusi tulisi vastata
Tekeekö verkkopalvelu työnsä - seitsemän kysymystä, joihin sivusi tulisi vastata
 
Johtaja sisällöntuottajana - näin aion onnistua
Johtaja sisällöntuottajana - näin aion onnistuaJohtaja sisällöntuottajana - näin aion onnistua
Johtaja sisällöntuottajana - näin aion onnistua
 
Arvaa selvitä kerro - käyttäjän odotukset verkkopalvelulta
Arvaa selvitä kerro - käyttäjän odotukset verkkopalvelultaArvaa selvitä kerro - käyttäjän odotukset verkkopalvelulta
Arvaa selvitä kerro - käyttäjän odotukset verkkopalvelulta
 
Tee ainakin nämä
Tee ainakin nämäTee ainakin nämä
Tee ainakin nämä
 
Verkkoviestintäpäivä 1/2
Verkkoviestintäpäivä 1/2Verkkoviestintäpäivä 1/2
Verkkoviestintäpäivä 1/2
 

Recently uploaded

WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 

Recently uploaded (20)

WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 

Tech friday 22.01.2016

  • 1. Asynchronous JavaScript Anssi Kinnunen (@anssikin) Tech friday 22.01.2016
  • 2. Asynchrony (programming): “Refers to the occurrence of events independently of the main program flow” https://en.wikipedia.org/wiki/Asynchrony_(computer_programming)
  • 3. JavaScript ● Event loop -based concurrency model ● Almost all I/O is non-blocking ● Single thread, ask runtime to perform operation, provide callback and move on to other tasks https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/ http://www.2ality.com/2014/09/es6-promises-foundations.html
  • 4. JavaScript runtime ● Contains a message queue ● Each message is associated with a callback function ● $(‘.btn’).click((evt) => { … }) ○ Click (external event) causes message to be queued https://developer.mozilla. org/en/docs/Web/JavaScript/EventLoop http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop- http://www.2ality.com/2014/09/es6-promises-foundations.html
  • 6. JavaScript event loop ● Synchronously processes message queue ● Each message is processed completely before others ○ When callback returns, event loop continues ● window.setTimeout(cb, wait) https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/ http://www.2ality.com/2014/09/es6-promises-foundations.html
  • 7. function () { console.log('this is the start'); window.setTimeout(() => { console.log('this is a msg from call back'); }); console.log('this is just a message'); window.setTimeout(() => { console.log('this is a msg from call back1'); }, 0); console.log('this is the end'); }
  • 8. JavaScript event loop ● Browser tab is controlled by a single process ● UI, other computations ● Blocking the event queue? https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/ http://www.2ality.com/2014/09/es6-promises-foundations.html
  • 9. Web Workers ● API designed to allow running scripts in background threads ● Worker has separate message queue, event loop and memory space, independent from originating thread https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/
  • 10. https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/ // pi_calculator.js let reportResult = (e) => { let pi = computePiToSpecifiedDecimals(e.data); postMessage(pi); }; onmessage = reportResult; // main code let piWorker = new Worker(‘pi_calculator.js’); let logResult = (e) => { console.log(`PI: ${e.data}`); }; piWorker.addEventListener(‘message’, logResult, false); piWorker.postMessage(100000);
  • 12. Promise ● Represents (‘proxy’) operation that hasn’t completed yet ● Promise is always in one of three states ○ Pending: result has not been computed, yet ○ Fulfilled: result was computed succesfully ○ Rejected: failure occurred during computation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise http://www.2ality.com/2014/10/es6-promises-api.html
  • 13. Promise ● Promise.all( [ ] ), Promise.race( [ ] ) ● Chaining: then() and catch() return promises ○ Promise() -> then() -> then() -> catch() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise http://www.2ality.com/2014/10/es6-promises-api.html
  • 14. let doHeavyCalculation = (a, b) => { return new Promise((resolve, reject) => { console.log('wait 2000ms'); window.setTimeout(() => { resolve(a + b); }, 2000); }); }; doHeavyCalculation(4, 4).then((result) => { return doHeavyCalculation(result, 2); }).then((calculatedValue) => { console.log(`the result is ${calculatedValue}`); });
  • 15. http://www.2ality.com/2014/10/es6-promises-api.html // Node.js style async file reading fs.readFile(‘config.json’, (error, text) => { if (error) { console.error(‘Error while reading config file’); } else { try { let obj = JSON.parse(text); console.log(JSON.stringify(obj, null, 4)); } catch (e) { console.error(‘Invalid JSON in file’); } } }); // Same functionality with promises readFilePromisified(‘config.json’) .then((text) => { let obj = JSON.parse(text); console.log(JSON.stringify(obj, null, 4)); }) .catch((reason) => { console.error(`An error occurred ${reason}`); });
  • 17. const request = require('request'); function getQuote() { return new Promise((resolve, reject) => { let url = 'http://ron-swanson-quotes.herokuapp.com/v2/quotes'; request(url, (error, response, quote) => { if (error) { reject(error); } else { resolve(quote); } }); }); } async function main() { try { let quote = await getQuote(); console.log(quote); } catch (e) { console.error(e); } } main(); https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html
  • 19. AJAX ● Group of technologies for async web ○ HTML/CSS, XML/XSLT, DOM ● Data passed is usually JSON
  • 21. let request; // Old compatibility code, no longer needed. if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ... request = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE 6 and older request = new ActiveXObject("Microsoft.XMLHTTP"); } request.onreadystatechange = () => { if (request.readyState === 4 && request.status === 200) { console.log(request.responseText); } } request.open('GET', 'http://davidwalsh.name/ajax-endpoint', true); request.send(null); https://davidwalsh.name/xmlhttprequest https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
  • 24. https://developer.mozilla.org/en/docs/Web/API/Fetch_API Fetch ● Interface for fetching resources, not finalized yet ● Like XHR, but more powerful ● window.fetch() -> Promise() -> Response
  • 25. // Chaining for more "advanced" handling fetch('/some/url').then((response) => { return //... }).then((returnedValue) => { // ... }).catch((err) => { // Error :( }); https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html