SlideShare a Scribd company logo
JavaScript Promises
Haim Michael
October 1th, 2024
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
life
michae
l
Simplified
© 2008 Haim Michael
Introduction
v ECMAScript 2015 provides us with the possibility to use
promises in our code.
v Promises allow us to to write code that executes
asynchronously. Promises allow us to write code that will be
executed at a later stage, and if succeeded or failed, a
notification will be generated accordingly.
v We can chain promises together based on success or failure
in a simpler easy to understand way.
© 2008 Haim Michael
Single Thread
v JavaScript has a single thread that handles a queue of jobs.
Whenever a new piece of code is ready to be executed it will
be added to the queue.
v When the JavaScript engine completes the execution of
specific job the event loop picks the next job in the queue and
executes it.
© 2008 Haim Michael
The Event Loop
v The event loop monitors the code execution and manages the
jobs queue. The jobs on that queue are executed according to
their order.
© 2008 Haim Michael
The Event Loop
v When a user clicks a button or presses a key on the keyboard
an event is triggered.
v The triggered event can be hooked with the code we want to
be executed whenever that event is triggered. The code we
hooked with the event will be added as a new job to the
queue.
© 2008 Haim Michael
The Callback Pattern
v The callback function is passed over as an argument. The
callback pattern makes it simple to chain multiple calls
together.
© 2008 Haim Michael
The Callback Pattern
func1("temp.txt", function(...) {
...
});
© 2008 Haim Michael
The Callback Hell Pattern
v When using the callback pattern and nesting too many
callbacks it can easily result in code that is hard to understand
and difficult to debug.
© 2008 Haim Michael
The Callback Hell Pattern
func1(function(err, result) {
...
func2(function(err, result) {
...
func3(function(err, result) {
...
func4(function(err, result) {
...
});
});
});
});
© 2008 Haim Michael
Problems of Higher Complexity
v When coping with problems of an higher complexity, such as
having two asynchronous operations running in parallel and
having another function we want to execute when the first two
completes.
© 2008 Haim Michael
Promise Basics
v Using the Promise constructor function we can create an
object that represents the result of an asynchronous
operation.
© 2008 Haim Michael
Promise Lifecycle
v Each and every promise goes through a short lifecycle. It
starts in the pending state (the asynchronous operation has
not yet completed).
v Once the asynchronous operation completes, the promise is
considered settled and enters one of two possible states:
fulfilled (the asynchronous operation has completed
successfully) or rejected (the asynchronous operation did not
complete successfully due to some error or another cause).
© 2008 Haim Michael
Promise Lifecycle
v We can take a specific action when a promise changes state
by using the then() method.
© 2008 Haim Michael
The then Method
vWe invoke the then() method on a Promise object. It can
take two functions.
© 2008 Haim Michael
The Promise Constructor
v We can create new promises by calling the Promise function
constructor. The Promise function receives a single
argument, which is the function that contains the code to be
executed when the promise is added to the queue.
v The function we pass over to Promise should be with two
parameters that receive two functions as arguments. The
resolve() and the reject().
© 2008 Haim Michael
The Promise Constructor
v The resolve() function should be called when the executor
has finished successfully in order to signal that the promise is
ready to be resolved.
v The reject() function should be called when the executor
function fails and we want to indicate about it.
© 2008 Haim Michael
The Promise Constructor
var promise = new Promise(function(resolve, reject) {
document.write("<br/>promise was created!");
resolve();
});
promise.then(function() {
document.write("<br/>the promise's executor completed... then one!");
}).then(function() {
document.write("<br/>the promise's executor completed... then two!");
}).then(function() {
document.write("<br/>the promise's executor completed... then three!");
});
document.write("<br/>simple output!");
© 2008 Haim Michael
The Promise Constructor
© 2008 Haim Michael
The catch Method
vThe catch() function is called when the executor
(represented by the promise object) fails. We should indicate
about that failure by calling the reject() function.
© 2008 Haim Michael
The catch Method
var promise = new Promise(function(resolve, reject) {
document.write("<br/>promise was created!");
//resolve();
reject();
});
promise.then(function() {
document.write("<br/>the promise's executor completed... then one!");
}).then(function() {
document.write("<br/>the promise's executor completed... then two!");
}).then(function() {
document.write("<br/>the promise's executor completed... then three!");
}).catch(function() {
document.write("<br/>inside catch");
});
document.write("<br/>simple output!");
© 2008 Haim Michael
The catch Method
© 2008 Haim Michael
Async Functions
v An async function is a function declared with the async
keyword, and the await keyword is permitted within it.
v The async and await keywords enable asynchronous,
promise-based behavior to be written in a cleaner style,
avoiding the need to explicitly configure promise chains.
© 2008 Haim Michael
Async Functions
console.log("line #10");
function f1() {
return new Promise(resolve => {
setTimeout(() => {
resolve('result');
}, 3000);
});
}
console.log("line #20");
async function f2() {
console.log('f2 start');
const result = await f1();
console.log(result);
console.log('f2 ends');
}
console.log("line #29");
f2();
console.log("line #33");
© 2008 Haim Michael
Async Functions
v We can specify the code we want to take place when the
promise fails by calling the catch method on the Promise
object the async function returns.
© 2008 Haim Michael
Async Functions
console.log("line #10");
function f1() {
return new Promise((resolve,reject) => {
setTimeout(() => {
//resolve('[{"code":"USD,"rate":3.1}, {"code":"GBP","rate":4.2}]');
reject("problem...");
}, 3000);
});
}
console.log("line #21");
async function f2() {
console.log('f2 start');
const result = await f1();
console.log(result);
console.log('f2 ends');
}
console.log("line #30");
f2().catch((data)=>{console.log("error took place data="+data);})
console.log("line #34");
© 2008 Haim Michael 20230307
Questions & Answers
Thanks for Your Time!
Haim Michael
haim.michael@lifemichael.com
+972+3+3726013 ext:700
life
michae
l
Ad

More Related Content

Similar to JavaScript Promises Simplified [Free Meetup] (20)

The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
Domenic Denicola
 
Javascripts hidden treasures BY - https://geekyants.com/
Javascripts hidden treasures            BY  -  https://geekyants.com/Javascripts hidden treasures            BY  -  https://geekyants.com/
Javascripts hidden treasures BY - https://geekyants.com/
Geekyants
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
slicejs
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
Knoldus Inc.
 
TDC2016POA | Trilha JavaScript - JavaScript Promises na Prática
TDC2016POA | Trilha JavaScript - JavaScript Promises na PráticaTDC2016POA | Trilha JavaScript - JavaScript Promises na Prática
TDC2016POA | Trilha JavaScript - JavaScript Promises na Prática
tdc-globalcode
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]
srikanthbkm
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
michael.labriola
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
Ivano Malavolta
 
JavaScript
JavaScriptJavaScript
JavaScript
Ivano Malavolta
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
Henrique Barcelos
 
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2
Rob Tweed
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
Laurence Svekis ✔
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
Asa Kusuma
 
Flex3 Deep Dive Final
Flex3 Deep Dive FinalFlex3 Deep Dive Final
Flex3 Deep Dive Final
RJ Owen
 
wp-UNIT_III.pptx
wp-UNIT_III.pptxwp-UNIT_III.pptx
wp-UNIT_III.pptx
GANDHAMKUMAR2
 
Web technologies-course 12.pptx
Web technologies-course 12.pptxWeb technologies-course 12.pptx
Web technologies-course 12.pptx
Stefan Oprea
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
Kamal S
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdf
HASENSEID
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
Domenic Denicola
 
Javascripts hidden treasures BY - https://geekyants.com/
Javascripts hidden treasures            BY  -  https://geekyants.com/Javascripts hidden treasures            BY  -  https://geekyants.com/
Javascripts hidden treasures BY - https://geekyants.com/
Geekyants
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
slicejs
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
Knoldus Inc.
 
TDC2016POA | Trilha JavaScript - JavaScript Promises na Prática
TDC2016POA | Trilha JavaScript - JavaScript Promises na PráticaTDC2016POA | Trilha JavaScript - JavaScript Promises na Prática
TDC2016POA | Trilha JavaScript - JavaScript Promises na Prática
tdc-globalcode
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]
srikanthbkm
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
michael.labriola
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
Henrique Barcelos
 
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2
EWD 3 Training Course Part 38: Building a React.js application with QEWD, Part 2
Rob Tweed
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
Laurence Svekis ✔
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
Asa Kusuma
 
Flex3 Deep Dive Final
Flex3 Deep Dive FinalFlex3 Deep Dive Final
Flex3 Deep Dive Final
RJ Owen
 
Web technologies-course 12.pptx
Web technologies-course 12.pptxWeb technologies-course 12.pptx
Web technologies-course 12.pptx
Stefan Oprea
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
Kamal S
 
Ch3- Java Script.pdf
Ch3- Java Script.pdfCh3- Java Script.pdf
Ch3- Java Script.pdf
HASENSEID
 

More from Haim Michael (20)

Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Haim Michael
 
Introduction to Pattern Matching in Java [Free Meetup]
Introduction to Pattern Matching in Java [Free Meetup]Introduction to Pattern Matching in Java [Free Meetup]
Introduction to Pattern Matching in Java [Free Meetup]
Haim Michael
 
Mastering The Collections in JavaScript [Free Meetup]
Mastering The Collections in JavaScript [Free Meetup]Mastering The Collections in JavaScript [Free Meetup]
Mastering The Collections in JavaScript [Free Meetup]
Haim Michael
 
Beyond Java - Evolving to Scala and Kotlin
Beyond Java - Evolving to Scala and KotlinBeyond Java - Evolving to Scala and Kotlin
Beyond Java - Evolving to Scala and Kotlin
Haim Michael
 
Scala Jump Start [Free Online Meetup in English]
Scala Jump Start [Free Online Meetup in English]Scala Jump Start [Free Online Meetup in English]
Scala Jump Start [Free Online Meetup in English]
Haim Michael
 
The MVVM Architecture in Java [Free Meetup]
The MVVM Architecture in Java [Free Meetup]The MVVM Architecture in Java [Free Meetup]
The MVVM Architecture in Java [Free Meetup]
Haim Michael
 
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Haim Michael
 
Anti Patterns
Anti PatternsAnti Patterns
Anti Patterns
Haim Michael
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
Haim Michael
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
Haim Michael
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
Haim Michael
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
Haim Michael
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
Haim Michael
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
Haim Michael
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
Haim Michael
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
Haim Michael
 
Java Jump Start
Java Jump StartJava Jump Start
Java Jump Start
Haim Michael
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
Haim Michael
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
Haim Michael
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHP
Haim Michael
 
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Typing in Python: Bringing Clarity, Safety and Speed to Your Code [Free Meetup]
Haim Michael
 
Introduction to Pattern Matching in Java [Free Meetup]
Introduction to Pattern Matching in Java [Free Meetup]Introduction to Pattern Matching in Java [Free Meetup]
Introduction to Pattern Matching in Java [Free Meetup]
Haim Michael
 
Mastering The Collections in JavaScript [Free Meetup]
Mastering The Collections in JavaScript [Free Meetup]Mastering The Collections in JavaScript [Free Meetup]
Mastering The Collections in JavaScript [Free Meetup]
Haim Michael
 
Beyond Java - Evolving to Scala and Kotlin
Beyond Java - Evolving to Scala and KotlinBeyond Java - Evolving to Scala and Kotlin
Beyond Java - Evolving to Scala and Kotlin
Haim Michael
 
Scala Jump Start [Free Online Meetup in English]
Scala Jump Start [Free Online Meetup in English]Scala Jump Start [Free Online Meetup in English]
Scala Jump Start [Free Online Meetup in English]
Haim Michael
 
The MVVM Architecture in Java [Free Meetup]
The MVVM Architecture in Java [Free Meetup]The MVVM Architecture in Java [Free Meetup]
The MVVM Architecture in Java [Free Meetup]
Haim Michael
 
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Kotlin Jump Start Online Free Meetup (June 4th, 2024)
Haim Michael
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
Haim Michael
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
Haim Michael
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
Haim Michael
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
Haim Michael
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
Haim Michael
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
Haim Michael
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
Haim Michael
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
Haim Michael
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
Haim Michael
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
Haim Michael
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHP
Haim Michael
 
Ad

Recently uploaded (20)

Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Ad

JavaScript Promises Simplified [Free Meetup]

  • 1. JavaScript Promises Haim Michael October 1th, 2024 All logos, trade marks and brand names used in this presentation belong to the respective owners. life michae l Simplified
  • 2. © 2008 Haim Michael Introduction v ECMAScript 2015 provides us with the possibility to use promises in our code. v Promises allow us to to write code that executes asynchronously. Promises allow us to write code that will be executed at a later stage, and if succeeded or failed, a notification will be generated accordingly. v We can chain promises together based on success or failure in a simpler easy to understand way.
  • 3. © 2008 Haim Michael Single Thread v JavaScript has a single thread that handles a queue of jobs. Whenever a new piece of code is ready to be executed it will be added to the queue. v When the JavaScript engine completes the execution of specific job the event loop picks the next job in the queue and executes it.
  • 4. © 2008 Haim Michael The Event Loop v The event loop monitors the code execution and manages the jobs queue. The jobs on that queue are executed according to their order.
  • 5. © 2008 Haim Michael The Event Loop v When a user clicks a button or presses a key on the keyboard an event is triggered. v The triggered event can be hooked with the code we want to be executed whenever that event is triggered. The code we hooked with the event will be added as a new job to the queue.
  • 6. © 2008 Haim Michael The Callback Pattern v The callback function is passed over as an argument. The callback pattern makes it simple to chain multiple calls together.
  • 7. © 2008 Haim Michael The Callback Pattern func1("temp.txt", function(...) { ... });
  • 8. © 2008 Haim Michael The Callback Hell Pattern v When using the callback pattern and nesting too many callbacks it can easily result in code that is hard to understand and difficult to debug.
  • 9. © 2008 Haim Michael The Callback Hell Pattern func1(function(err, result) { ... func2(function(err, result) { ... func3(function(err, result) { ... func4(function(err, result) { ... }); }); }); });
  • 10. © 2008 Haim Michael Problems of Higher Complexity v When coping with problems of an higher complexity, such as having two asynchronous operations running in parallel and having another function we want to execute when the first two completes.
  • 11. © 2008 Haim Michael Promise Basics v Using the Promise constructor function we can create an object that represents the result of an asynchronous operation.
  • 12. © 2008 Haim Michael Promise Lifecycle v Each and every promise goes through a short lifecycle. It starts in the pending state (the asynchronous operation has not yet completed). v Once the asynchronous operation completes, the promise is considered settled and enters one of two possible states: fulfilled (the asynchronous operation has completed successfully) or rejected (the asynchronous operation did not complete successfully due to some error or another cause).
  • 13. © 2008 Haim Michael Promise Lifecycle v We can take a specific action when a promise changes state by using the then() method.
  • 14. © 2008 Haim Michael The then Method vWe invoke the then() method on a Promise object. It can take two functions.
  • 15. © 2008 Haim Michael The Promise Constructor v We can create new promises by calling the Promise function constructor. The Promise function receives a single argument, which is the function that contains the code to be executed when the promise is added to the queue. v The function we pass over to Promise should be with two parameters that receive two functions as arguments. The resolve() and the reject().
  • 16. © 2008 Haim Michael The Promise Constructor v The resolve() function should be called when the executor has finished successfully in order to signal that the promise is ready to be resolved. v The reject() function should be called when the executor function fails and we want to indicate about it.
  • 17. © 2008 Haim Michael The Promise Constructor var promise = new Promise(function(resolve, reject) { document.write("<br/>promise was created!"); resolve(); }); promise.then(function() { document.write("<br/>the promise's executor completed... then one!"); }).then(function() { document.write("<br/>the promise's executor completed... then two!"); }).then(function() { document.write("<br/>the promise's executor completed... then three!"); }); document.write("<br/>simple output!");
  • 18. © 2008 Haim Michael The Promise Constructor
  • 19. © 2008 Haim Michael The catch Method vThe catch() function is called when the executor (represented by the promise object) fails. We should indicate about that failure by calling the reject() function.
  • 20. © 2008 Haim Michael The catch Method var promise = new Promise(function(resolve, reject) { document.write("<br/>promise was created!"); //resolve(); reject(); }); promise.then(function() { document.write("<br/>the promise's executor completed... then one!"); }).then(function() { document.write("<br/>the promise's executor completed... then two!"); }).then(function() { document.write("<br/>the promise's executor completed... then three!"); }).catch(function() { document.write("<br/>inside catch"); }); document.write("<br/>simple output!");
  • 21. © 2008 Haim Michael The catch Method
  • 22. © 2008 Haim Michael Async Functions v An async function is a function declared with the async keyword, and the await keyword is permitted within it. v The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
  • 23. © 2008 Haim Michael Async Functions console.log("line #10"); function f1() { return new Promise(resolve => { setTimeout(() => { resolve('result'); }, 3000); }); } console.log("line #20"); async function f2() { console.log('f2 start'); const result = await f1(); console.log(result); console.log('f2 ends'); } console.log("line #29"); f2(); console.log("line #33");
  • 24. © 2008 Haim Michael Async Functions v We can specify the code we want to take place when the promise fails by calling the catch method on the Promise object the async function returns.
  • 25. © 2008 Haim Michael Async Functions console.log("line #10"); function f1() { return new Promise((resolve,reject) => { setTimeout(() => { //resolve('[{"code":"USD,"rate":3.1}, {"code":"GBP","rate":4.2}]'); reject("problem..."); }, 3000); }); } console.log("line #21"); async function f2() { console.log('f2 start'); const result = await f1(); console.log(result); console.log('f2 ends'); } console.log("line #30"); f2().catch((data)=>{console.log("error took place data="+data);}) console.log("line #34");
  • 26. © 2008 Haim Michael 20230307 Questions & Answers Thanks for Your Time! Haim Michael [email protected] +972+3+3726013 ext:700 life michae l