SlideShare a Scribd company logo
1 of 18
Download to read offline
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
 
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
 

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

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

Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
Vaclav Pech
 

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

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

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Recently uploaded (20)

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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
%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
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
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...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 

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