SlideShare a Scribd company logo
1 of 22
Javascript Promises
Alok Guha
JS Functions
• Functions are first class citizens in JavaScript
• Functions can take functions as arguments
and call them when they are done.
First-class functions
function sqr(x) {
return x * x; }
// a function may be assigned to a variable
var func = sqr;
// a function may have properties or be a property
func.doubleMe = function (x) {
return x + x;
};
// a function may be used as a parameter
[1, 2, 3].map(func.doubleMe); OR
[1, 2, 3].map(func);
First-class functions
function calculate(config){
//choose a function based on ref data
return config.flag ? sqr : cube;
}

function sqr(x){ return x*x; }
function cube(x){ return sqr(x)*x; }
Callbacks
• Callback functions are derived from a programming
paradigm called functional programming.(At a simple and
fundamental level, functional programming is the use of functions as arguments)

fileSys.readFile("file1.txt", function (file1Content) {
return file1Content;
});

.
Is Javascript really Async ?
• All of the JavaScript engines including V8
Engine are single-threaded.
• But all I/O is evented and asynchronous It is
possible via the EventLoop.
Event Loops
• An entity that handles and processes external
events and converts them into callback
invocations
• Every asynchronous operation adds itself to
the EventLoop Event Loops
How it works ?
Promise
“A declaration or assurance that one will do
something or that a particular thing will
happen”

• A Promise can be
– Pending
– Fulfilled
– Rejected
JS Promise
• A Promise is an object that represents a onetime event, typically the outcome of an async
task like an AJAX call.
• At first, a Promise is in a pending state.
Eventually, it’s either resolved or rejected.
• Once a Promise is resolved or rejected, it’ll
remain in that state forever, and its callbacks
will never fire again
How to promise ?
var promise = new Promise(function(resolve, reject){
// do a thing, possibly async, then…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
Lets promise..
var num = 4;
var simpleSqrPromise = new Promise(function(resolve, reject){
resolve(num*num);
reject();
});
//execute it
simpleSqrPromise.then(function(data){
console.log("worked "+data);
}).catch(function(err){ console.log(err);});
Simple Functional Transform
var user = getUser();
var userName = user.name;

// becomes
var userNamePromise = getUser().then(function (user) { return
user.name; });
Simple coding path
• Can we code a Promise which parses JSON ?
And ensure its value for next operation..
Do you know them ?
Consider this ;/
Callbacks are hell :D
• They are literally the simplest thing that could work.
• But as a replacement for synchronous control flow,
they s**k.
• There’s no consistency in callback APIs.
• There’s no guarantees.
• We lose the flow of our code writing callbacks that tie
together other callbacks.
• We lose the stack-unwinding semantics of exceptions,
forcing us to handle errors explicitly at every step.
Now see this..
someCall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function(value4){
// do something
})
.done();
Promise Guarantees
promiseForResult.then(onFulfilled, onRejected);

•

Only one of onFulfilled or onRejected will be called.

•

onFulfilled will be called with a single fulfillment value (⇔ return
value).

•

onRejected will be called with a single rejection reason (⇔ thrown
exception).

•

If the promise is already settled, the handlers will still be called once
you attach them.

•

The handlers will always be called asynchronously.
JS Promise frameworks
• Jquery Promise
• When
• Q
• A+
• JSPromise
Etc..
References
•
•
•
•
•
•

Google.com 
..
..
..
..
..
Thanks

More Related Content

What's hot

Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
Domenic Denicola
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
Taha Shakeel
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 

What's hot (20)

Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Mule esb object_to_jackson_json
Mule esb object_to_jackson_jsonMule esb object_to_jackson_json
Mule esb object_to_jackson_json
 
Async Frontiers
Async FrontiersAsync Frontiers
Async Frontiers
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
 

Similar to Java Script Promise

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 

Similar to Java Script Promise (20)

Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Declarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetationDeclarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetation
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Async all around us (promises)
Async all around us (promises)Async all around us (promises)
Async all around us (promises)
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
OSCON - ES6 metaprogramming unleashed
OSCON -  ES6 metaprogramming unleashedOSCON -  ES6 metaprogramming unleashed
OSCON - ES6 metaprogramming unleashed
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Functions - complex first class citizen
Functions - complex first class citizenFunctions - complex first class citizen
Functions - complex first class citizen
 
Functional programming in javascript
Functional programming in javascriptFunctional programming in javascript
Functional programming in javascript
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 

More from Alok Guha (6)

Aglie estimation and planning
Aglie estimation and planningAglie estimation and planning
Aglie estimation and planning
 
Q unit
Q unitQ unit
Q unit
 
Express JS
Express JSExpress JS
Express JS
 
Jasmine
JasmineJasmine
Jasmine
 
Design patterns
Design patternsDesign patterns
Design patterns
 
NodeJS
NodeJSNodeJS
NodeJS
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 

Java Script Promise

  • 2. JS Functions • Functions are first class citizens in JavaScript • Functions can take functions as arguments and call them when they are done.
  • 3. First-class functions function sqr(x) { return x * x; } // a function may be assigned to a variable var func = sqr; // a function may have properties or be a property func.doubleMe = function (x) { return x + x; }; // a function may be used as a parameter [1, 2, 3].map(func.doubleMe); OR [1, 2, 3].map(func);
  • 4. First-class functions function calculate(config){ //choose a function based on ref data return config.flag ? sqr : cube; } function sqr(x){ return x*x; } function cube(x){ return sqr(x)*x; }
  • 5. Callbacks • Callback functions are derived from a programming paradigm called functional programming.(At a simple and fundamental level, functional programming is the use of functions as arguments) fileSys.readFile("file1.txt", function (file1Content) { return file1Content; }); .
  • 6. Is Javascript really Async ? • All of the JavaScript engines including V8 Engine are single-threaded. • But all I/O is evented and asynchronous It is possible via the EventLoop.
  • 7. Event Loops • An entity that handles and processes external events and converts them into callback invocations • Every asynchronous operation adds itself to the EventLoop Event Loops
  • 9. Promise “A declaration or assurance that one will do something or that a particular thing will happen” • A Promise can be – Pending – Fulfilled – Rejected
  • 10. JS Promise • A Promise is an object that represents a onetime event, typically the outcome of an async task like an AJAX call. • At first, a Promise is in a pending state. Eventually, it’s either resolved or rejected. • Once a Promise is resolved or rejected, it’ll remain in that state forever, and its callbacks will never fire again
  • 11. How to promise ? var promise = new Promise(function(resolve, reject){ // do a thing, possibly async, then… if (/* everything turned out fine */) { resolve("Stuff worked!"); } else { reject(Error("It broke")); } });
  • 12. Lets promise.. var num = 4; var simpleSqrPromise = new Promise(function(resolve, reject){ resolve(num*num); reject(); }); //execute it simpleSqrPromise.then(function(data){ console.log("worked "+data); }).catch(function(err){ console.log(err);});
  • 13. Simple Functional Transform var user = getUser(); var userName = user.name; // becomes var userNamePromise = getUser().then(function (user) { return user.name; });
  • 14. Simple coding path • Can we code a Promise which parses JSON ? And ensure its value for next operation..
  • 15. Do you know them ?
  • 17. Callbacks are hell :D • They are literally the simplest thing that could work. • But as a replacement for synchronous control flow, they s**k. • There’s no consistency in callback APIs. • There’s no guarantees. • We lose the flow of our code writing callbacks that tie together other callbacks. • We lose the stack-unwinding semantics of exceptions, forcing us to handle errors explicitly at every step.
  • 19. Promise Guarantees promiseForResult.then(onFulfilled, onRejected); • Only one of onFulfilled or onRejected will be called. • onFulfilled will be called with a single fulfillment value (⇔ return value). • onRejected will be called with a single rejection reason (⇔ thrown exception). • If the promise is already settled, the handlers will still be called once you attach them. • The handlers will always be called asynchronously.
  • 20. JS Promise frameworks • Jquery Promise • When • Q • A+ • JSPromise Etc..