SlideShare a Scribd company logo
CALLBACKS,
PROMISES,
GENERATORS
Adam Gołąb
Full Stack Developer at
In computer programming, a callback is a piece of executable code
that is passed as an argument to other code, which is expected to
call back (execute) the argument at some convenient time.
Callbacks
Good Practice
Run ►
function validate(email, cb) {
if (email.match(/^[a-zA-Z0-9]+@[a-zA-Z0-9]+(.[a-zA-Z0-9]+)+$/)) {
return cb(null, email);
}
return cb(new Error('incorrect email address'));
}
validate('email@example.com', (err, email) => {
if (err) {
return console.log(err);
}
console.log('Successfully validated:', email);
});
Successfully validated: email@example.com
1
2
3
4
5
6
7
8
9
10
11
12
13
For a function to be asynchronous it needs to perform an
asynchronous operation. It needs to incorporate the argument
callback in handling the results of this asynchronous operation.
Only this way the function becomes asynchronous.
Asynchronous
Async Callback
Run ►
function callAsync(fn) {
setTimeout(fn, 0);
}
callAsync(() => console.log('callback function'));
console.log('after');
after
callback function
1
2
3
4
5
6
AJAX request
Run ►
const request = require('request');
request('http://localhost:3000/api', (err, res, body) => console.log(body));
Response from server
1
2
3
IO operation
Run ►
const fs = require('fs');
fs.readFile('./file.txt', 'utf-8', (err, data) => {
if(!err) {
console.log(data);
}
});
Hello from file
1
2
3
4
5
6
7
Pyramid from hell
Run ►
const request = require('request');
const fs = require('fs');
request('http://localhost:3000/api', (err, res, body) => {
if (!err) {
fs.readFile('./file.txt', 'utf-8', (err, data) => {
if (!err) {
[data, body].map((text, index) => {
console.log(index, text);
});
}
});
}
});
0 'Hello from filen'
1 'Response from server'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
PromisesThe Promise object is used for asynchronous computations. A
Promise represents a value which may be available now, or in the
future, or never.
new Promise( function(resolve, reject) { ... } );
Promises
Run ►
const a = 4;
const b = 2;
const p = new Promise((resolve, reject) => {
if (b === 0) {
reject(new Error('Do not divide by zero'));
}
resolve(a / b);
});
p.then(value => console.log(value)).catch(err => console.error(err));
2
1
2
3
4
5
6
7
8
9
10
AJAX Fetch
Run ►
const fetch = require('node-fetch'); // there is no window.fetch on node.js
fetch('http://localhost:3000/api')
.then(res => res.text())
.then(body => console.log(body));
Response from server
1
2
3
4
5
Run ►
No more callback hellconst fetch = require('node-fetch');
const fs = require('fs');
function readFilePromised(file) {
const p = new Promise((resolve, reject) => {
fs.readFile(file, 'utf-8', (err, data) => {
if (err) {
reject(err);
}
resolve(data);
});
});
return p;
}
Promise.all([
readFilePromised('./file.txt'),
fetch('http://localhost:3000/api').then(r => r.text())
])
.then((responses) => responses.map((text, index) => {
console.log(index, text);
}));
0 'Hello from filen'
1 'Response from server'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Generators
is a special routine that can be used to control the iteration
behaviour of a loop. In fact, all generators are iterators
Pausable functions
Run ►
Natural numbers generator
function *naturalNumbers() {
let x = 0;
while (true) {
x = x + 1;
yield x;
}
}
const generator = naturalNumbers();
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
1
2
3
4
5
6
7
8
9
10
11
12
Async generator
Run ►
const fetch = require('node-fetch');
const co = require('co');
co(function *() {
const uri = 'http://localhost:3000/api';
const response = yield fetch(uri);
const body = yield response.text();
console.log(body);
});
Response from server
1
2
3
4
5
6
7
8
9
Run ►
Co function implementation
const fetch = require('node-fetch');
function co(generator) {
const iterator = generator();
const iteration = iterator.next();
function iterate(iteration) {
if (iteration.done) {
return iteration.value;
}
const promise = iteration.value;
return promise.then(x => iterate(iterator.next(x)));
}
return iterate(iteration);
}
co(function *() {
const uri = 'http://localhost:3000/api';
const response = yield fetch(uri);
const body = yield response.text();
console.log(body);
});
Response from server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Questions?

More Related Content

What's hot

オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
Takayuki Goto
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
pratikbakane
 
Oop1
Oop1Oop1
Data structure programs in c++
Data structure programs in c++Data structure programs in c++
Data structure programs in c++
mmirfan
 
Real world scala
Real world scalaReal world scala
Real world scala
lunfu zhong
 
1
11
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
Designveloper
 
Map kit light
Map kit lightMap kit light
Map kit light
CocoaHeads France
 
Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
Christoffer Noring
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
t k
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
C++ TUTORIAL 5
C++ TUTORIAL 5C++ TUTORIAL 5
C++ TUTORIAL 5
Farhan Ab Rahman
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
desistartups
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
 
Using Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasetsUsing Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasets
Bartosz Konieczny
 
Typelevel summit
Typelevel summitTypelevel summit
Typelevel summit
Marina Sigaeva
 
React native-firebase startup-mtup
React native-firebase startup-mtupReact native-firebase startup-mtup
React native-firebase startup-mtup
t k
 
Understanding the nodejs event loop
Understanding the nodejs event loopUnderstanding the nodejs event loop
Understanding the nodejs event loop
Saurabh Kumar
 

What's hot (20)

オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Oop1
Oop1Oop1
Oop1
 
Data structure programs in c++
Data structure programs in c++Data structure programs in c++
Data structure programs in c++
 
Real world scala
Real world scalaReal world scala
Real world scala
 
1
11
1
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Map kit light
Map kit lightMap kit light
Map kit light
 
Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
C++ TUTORIAL 5
C++ TUTORIAL 5C++ TUTORIAL 5
C++ TUTORIAL 5
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Using Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasetsUsing Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasets
 
Typelevel summit
Typelevel summitTypelevel summit
Typelevel summit
 
React native-firebase startup-mtup
React native-firebase startup-mtupReact native-firebase startup-mtup
React native-firebase startup-mtup
 
Understanding the nodejs event loop
Understanding the nodejs event loopUnderstanding the nodejs event loop
Understanding the nodejs event loop
 

Viewers also liked

Why and How You Should Move from PHP to Node.js
Why and How You Should Move from PHP to Node.jsWhy and How You Should Move from PHP to Node.js
Why and How You Should Move from PHP to Node.js
Brainhub
 
Lexical scope, function vs. block scope, hoisting, scope closures
Lexical scope, function vs. block scope, hoisting, scope closuresLexical scope, function vs. block scope, hoisting, scope closures
Lexical scope, function vs. block scope, hoisting, scope closures
Brainhub
 
Technologia, a Startup - Brainhub
Technologia, a Startup - BrainhubTechnologia, a Startup - Brainhub
Technologia, a Startup - Brainhub
Brainhub
 
JavaScript and Desktop Apps - Introduction to Electron
JavaScript and Desktop Apps - Introduction to ElectronJavaScript and Desktop Apps - Introduction to Electron
JavaScript and Desktop Apps - Introduction to Electron
Brainhub
 
How should you React to Redux
How should you React to ReduxHow should you React to Redux
How should you React to Redux
Brainhub
 
Wprowadzenie do React
Wprowadzenie do ReactWprowadzenie do React
Wprowadzenie do React
Brainhub
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
Brainhub
 

Viewers also liked (7)

Why and How You Should Move from PHP to Node.js
Why and How You Should Move from PHP to Node.jsWhy and How You Should Move from PHP to Node.js
Why and How You Should Move from PHP to Node.js
 
Lexical scope, function vs. block scope, hoisting, scope closures
Lexical scope, function vs. block scope, hoisting, scope closuresLexical scope, function vs. block scope, hoisting, scope closures
Lexical scope, function vs. block scope, hoisting, scope closures
 
Technologia, a Startup - Brainhub
Technologia, a Startup - BrainhubTechnologia, a Startup - Brainhub
Technologia, a Startup - Brainhub
 
JavaScript and Desktop Apps - Introduction to Electron
JavaScript and Desktop Apps - Introduction to ElectronJavaScript and Desktop Apps - Introduction to Electron
JavaScript and Desktop Apps - Introduction to Electron
 
How should you React to Redux
How should you React to ReduxHow should you React to Redux
How should you React to Redux
 
Wprowadzenie do React
Wprowadzenie do ReactWprowadzenie do React
Wprowadzenie do React
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 

Similar to All you need to know about Callbacks, Promises, Generators

Asynchronous programming with java script and node.js
Asynchronous programming with java script and node.jsAsynchronous programming with java script and node.js
Asynchronous programming with java script and node.js
Timur Shemsedinov
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
Ramesh Nair
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017
Colin Oakley
 
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
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programming
Masters Academy
 
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
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
Binary Studio
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
Vaclav Pech
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
Felix Geisendörfer
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
Node lt
Node ltNode lt
Node lt
snodar
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
Bruno Scopelliti
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
Christoffer Noring
 
Rxjs vienna
Rxjs viennaRxjs vienna
Rxjs vienna
Christoffer Noring
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more Reactive
Jeff Smith
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
Oscar Renalias
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
Juergen Fesslmeier
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 

Similar to All you need to know about Callbacks, Promises, Generators (20)

Asynchronous programming with java script and node.js
Asynchronous programming with java script and node.jsAsynchronous programming with java script and node.js
Asynchronous programming with java script and node.js
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programming
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Node lt
Node ltNode lt
Node lt
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Rxjs vienna
Rxjs viennaRxjs vienna
Rxjs vienna
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more Reactive
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
 

More from Brainhub

AWS – jak rozpocząć przygodę z chmurą?
AWS – jak rozpocząć przygodę z chmurą?AWS – jak rozpocząć przygodę z chmurą?
AWS – jak rozpocząć przygodę z chmurą?
Brainhub
 
Konfiguracja GitLab CI/CD pipelines od podstaw
Konfiguracja GitLab CI/CD pipelines od podstawKonfiguracja GitLab CI/CD pipelines od podstaw
Konfiguracja GitLab CI/CD pipelines od podstaw
Brainhub
 
tRPC - czy to koniec GraphQL?
tRPC - czy to koniec GraphQL?tRPC - czy to koniec GraphQL?
tRPC - czy to koniec GraphQL?
Brainhub
 
Solid.js - następca Reacta?
Solid.js - następca Reacta?Solid.js - następca Reacta?
Solid.js - następca Reacta?
Brainhub
 
Struktury algebraiczne w JavaScripcie
Struktury algebraiczne w JavaScripcieStruktury algebraiczne w JavaScripcie
Struktury algebraiczne w JavaScripcie
Brainhub
 
WebAssembly - czy dzisiaj mi się to przyda do pracy?
WebAssembly - czy dzisiaj mi się to przyda do pracy?WebAssembly - czy dzisiaj mi się to przyda do pracy?
WebAssembly - czy dzisiaj mi się to przyda do pracy?
Brainhub
 
Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!
Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!
Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!
Brainhub
 
Go home TypeScript, you're drunk!
Go home TypeScript, you're drunk!Go home TypeScript, you're drunk!
Go home TypeScript, you're drunk!
Brainhub
 
How I taught the messenger to tell lame jokes
How I taught the messenger to tell lame jokesHow I taught the messenger to tell lame jokes
How I taught the messenger to tell lame jokes
Brainhub
 
The hunt of the unicorn, to capture productivity
The hunt of the unicorn, to capture productivityThe hunt of the unicorn, to capture productivity
The hunt of the unicorn, to capture productivity
Brainhub
 
TDD in the wild
TDD in the wildTDD in the wild
TDD in the wild
Brainhub
 
WebAssembly - kolejny buzzword, czy (r)ewolucja?
WebAssembly - kolejny buzzword, czy (r)ewolucja?WebAssembly - kolejny buzzword, czy (r)ewolucja?
WebAssembly - kolejny buzzword, czy (r)ewolucja?
Brainhub
 
React performance
React performanceReact performance
React performance
Brainhub
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
Brainhub
 
React Native in a nutshell
React Native in a nutshellReact Native in a nutshell
React Native in a nutshell
Brainhub
 
Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)
Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)
Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)
Brainhub
 

More from Brainhub (16)

AWS – jak rozpocząć przygodę z chmurą?
AWS – jak rozpocząć przygodę z chmurą?AWS – jak rozpocząć przygodę z chmurą?
AWS – jak rozpocząć przygodę z chmurą?
 
Konfiguracja GitLab CI/CD pipelines od podstaw
Konfiguracja GitLab CI/CD pipelines od podstawKonfiguracja GitLab CI/CD pipelines od podstaw
Konfiguracja GitLab CI/CD pipelines od podstaw
 
tRPC - czy to koniec GraphQL?
tRPC - czy to koniec GraphQL?tRPC - czy to koniec GraphQL?
tRPC - czy to koniec GraphQL?
 
Solid.js - następca Reacta?
Solid.js - następca Reacta?Solid.js - następca Reacta?
Solid.js - następca Reacta?
 
Struktury algebraiczne w JavaScripcie
Struktury algebraiczne w JavaScripcieStruktury algebraiczne w JavaScripcie
Struktury algebraiczne w JavaScripcie
 
WebAssembly - czy dzisiaj mi się to przyda do pracy?
WebAssembly - czy dzisiaj mi się to przyda do pracy?WebAssembly - czy dzisiaj mi się to przyda do pracy?
WebAssembly - czy dzisiaj mi się to przyda do pracy?
 
Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!
Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!
Ewoluowanie neuronowych mózgów w JavaScript, wielowątkowo!
 
Go home TypeScript, you're drunk!
Go home TypeScript, you're drunk!Go home TypeScript, you're drunk!
Go home TypeScript, you're drunk!
 
How I taught the messenger to tell lame jokes
How I taught the messenger to tell lame jokesHow I taught the messenger to tell lame jokes
How I taught the messenger to tell lame jokes
 
The hunt of the unicorn, to capture productivity
The hunt of the unicorn, to capture productivityThe hunt of the unicorn, to capture productivity
The hunt of the unicorn, to capture productivity
 
TDD in the wild
TDD in the wildTDD in the wild
TDD in the wild
 
WebAssembly - kolejny buzzword, czy (r)ewolucja?
WebAssembly - kolejny buzzword, czy (r)ewolucja?WebAssembly - kolejny buzzword, czy (r)ewolucja?
WebAssembly - kolejny buzzword, czy (r)ewolucja?
 
React performance
React performanceReact performance
React performance
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
React Native in a nutshell
React Native in a nutshellReact Native in a nutshell
React Native in a nutshell
 
Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)
Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)
Ant Colony Optimization (Heuristic algorithms & Swarm intelligence)
 

Recently uploaded

ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 

Recently uploaded (20)

ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 

All you need to know about Callbacks, Promises, Generators

  • 2. Adam Gołąb Full Stack Developer at
  • 3. In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. Callbacks
  • 4. Good Practice Run ► function validate(email, cb) { if (email.match(/^[a-zA-Z0-9]+@[a-zA-Z0-9]+(.[a-zA-Z0-9]+)+$/)) { return cb(null, email); } return cb(new Error('incorrect email address')); } validate('email@example.com', (err, email) => { if (err) { return console.log(err); } console.log('Successfully validated:', email); }); Successfully validated: email@example.com 1 2 3 4 5 6 7 8 9 10 11 12 13
  • 5. For a function to be asynchronous it needs to perform an asynchronous operation. It needs to incorporate the argument callback in handling the results of this asynchronous operation. Only this way the function becomes asynchronous. Asynchronous
  • 6. Async Callback Run ► function callAsync(fn) { setTimeout(fn, 0); } callAsync(() => console.log('callback function')); console.log('after'); after callback function 1 2 3 4 5 6
  • 7. AJAX request Run ► const request = require('request'); request('http://localhost:3000/api', (err, res, body) => console.log(body)); Response from server 1 2 3
  • 8. IO operation Run ► const fs = require('fs'); fs.readFile('./file.txt', 'utf-8', (err, data) => { if(!err) { console.log(data); } }); Hello from file 1 2 3 4 5 6 7
  • 9. Pyramid from hell Run ► const request = require('request'); const fs = require('fs'); request('http://localhost:3000/api', (err, res, body) => { if (!err) { fs.readFile('./file.txt', 'utf-8', (err, data) => { if (!err) { [data, body].map((text, index) => { console.log(index, text); }); } }); } }); 0 'Hello from filen' 1 'Response from server' 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  • 10. PromisesThe Promise object is used for asynchronous computations. A Promise represents a value which may be available now, or in the future, or never. new Promise( function(resolve, reject) { ... } );
  • 11. Promises Run ► const a = 4; const b = 2; const p = new Promise((resolve, reject) => { if (b === 0) { reject(new Error('Do not divide by zero')); } resolve(a / b); }); p.then(value => console.log(value)).catch(err => console.error(err)); 2 1 2 3 4 5 6 7 8 9 10
  • 12. AJAX Fetch Run ► const fetch = require('node-fetch'); // there is no window.fetch on node.js fetch('http://localhost:3000/api') .then(res => res.text()) .then(body => console.log(body)); Response from server 1 2 3 4 5
  • 13. Run ► No more callback hellconst fetch = require('node-fetch'); const fs = require('fs'); function readFilePromised(file) { const p = new Promise((resolve, reject) => { fs.readFile(file, 'utf-8', (err, data) => { if (err) { reject(err); } resolve(data); }); }); return p; } Promise.all([ readFilePromised('./file.txt'), fetch('http://localhost:3000/api').then(r => r.text()) ]) .then((responses) => responses.map((text, index) => { console.log(index, text); })); 0 'Hello from filen' 1 'Response from server' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 14. Generators is a special routine that can be used to control the iteration behaviour of a loop. In fact, all generators are iterators Pausable functions
  • 15. Run ► Natural numbers generator function *naturalNumbers() { let x = 0; while (true) { x = x + 1; yield x; } } const generator = naturalNumbers(); console.log(generator.next()); console.log(generator.next()); console.log(generator.next()); { value: 1, done: false } { value: 2, done: false } { value: 3, done: false } 1 2 3 4 5 6 7 8 9 10 11 12
  • 16. Async generator Run ► const fetch = require('node-fetch'); const co = require('co'); co(function *() { const uri = 'http://localhost:3000/api'; const response = yield fetch(uri); const body = yield response.text(); console.log(body); }); Response from server 1 2 3 4 5 6 7 8 9
  • 17. Run ► Co function implementation const fetch = require('node-fetch'); function co(generator) { const iterator = generator(); const iteration = iterator.next(); function iterate(iteration) { if (iteration.done) { return iteration.value; } const promise = iteration.value; return promise.then(x => iterate(iterator.next(x))); } return iterate(iteration); } co(function *() { const uri = 'http://localhost:3000/api'; const response = yield fetch(uri); const body = yield response.text(); console.log(body); }); Response from server 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21