SlideShare uma empresa Scribd logo
1 de 28
Baixar para ler offline
Javascript Promises/Q library
            Jonathan Altman
          node.dc March 2013
               @async_io
             http://async.io/
What is a Promise?
The simplest explanation: it is an easy way to avoid writing the Pyramid of Doom
Pyramid of Doom
step1(function (value1) {

      step2(value1, function(value2) {

            step3(value2, function(value3) {

                  step4(value3, function(value4) {

                        // Do something with value4

                  });

            });

      });

});                // from https://github.com/kriskowal/q
Why Promises? What about?
•   async: http://github.com/caolan/async

•   step: https://github.com/creationix/step

•   flow-js: https://github.com/willconant/flow-js

•   ...you get the point
Non-Promises Fix:
async.series({
    normalize: function(callback){
        // Bodies removed for brevity
    }
    , compose: function(callback){
    }
    , invert: function(callback){
    }
    // A bunch more stuff killed
  }
  , function (err, results)
  {
    if (!err ) {
      err = new Error('Results did not contain a valid image buffer')
    }
    else {
      callback(err, results.imageBuffer);
    }
  }
}); //https://github.com/jonathana/heatNode/blob/master/lib/imageGen/generateimages.js
Is That Not Good Enough?
var later = Q.nfcall(nodedc.wait_a_few_slides);
               // or: we’ll come back to it
Promises: Longer Explanation
“A Promise is an object representation of an event. In the course of its
life, a Promise goes from a pending state, when it’s called, to a resolved or
rejected state, when it’s been completed, or it could also stay pending
forever and is never resolved.”

                http://flaviocopes.com/deferred-and-promises-in-javascript/
Say What?
•   Promises take a call to an asynchronous function and wrap it with an
    object whose methods proxy when the wrapped function either
    completes or errors

•   A good Promise library also provides a set of control methods on that
    object wrapper to handle composition of multiple Promise-ified
    asynchronous method calls

•   Promises use the best qualities of an object--encapsulation of state--to
    track the state of an asynchronous call
Promises provide a
        solid abstraction
         for representing the
  state of an asynchronous call
          and writing flow of
control code based on that state
Pyramid of Doom Again
step1(function (value1) {

      step2(value1, function(value2) {

            step3(value2, function(value3) {

                  step4(value3, function(value4) {

                        // Do something with value4

                  });

            });

      });

});                // from https://github.com/kriskowal/q
Pyramid of Doom on Promises
Q.fcall(step1) // This returns a Promise obj
.then(step2)
.then(step3)
.then(step4)
.then(function (value4) {
    // Do something with value4
}, function (error) {
    // Handle any error from step1 through step4
})
.done();   // from https://github.com/kriskowal/q
Again, Why Promises?
•   It’s a spec: http://wiki.commonjs.org/wiki/Promises/A

•   Generally supported by a bunch of libs both browser and server-side:

    •   jQuery (sort of, supposedly doesn’t fully work like Promises/A)

    •   AngularJS

    •   Q library (https://github.com/kriskowal/q)

•   Provides separation of concerns between wrapping and flow of control
    handling of deferred activities
later.then(function(){
Provides separation of concerns between wrapping and flow of
            control handling of deferred activities
              // that separation is the key
                           });
Promises can (mostly) be shared
        across libraries
Sharing
•   Many libraries can exchange Promise objects

•   AngularJS’ Promise API is explicitly based off a subset of Q. If Q is
    loads first, AngularJS just uses that

•   jQuery’s promises can be consumed by Q, with some adaptations
So Why Q?
•   Q consumes Promises from most other libraries

•   Pure Javascript library

•   Can be used both client-side (browser or e.g. Phonegap) and server-side (npm install
    q, but you’re using package.json, right?)

•   Provides utilities to make it easy to write Promise-based code or wrap non-Promise-
    based functions

•   Provides a library of methods to build control flow around Promise results and errors

•   Small (enough?): ~1400 SLOC, ~ 8.5kb minified
Generating Promises With Q
Q.fcall/nfcall: Wrap an Async
         method with a Promise
function writeError(errMessage) {
     return Q.nfcall(fs.writeFile, "errors.log",
errMessage);
}
• nfcall: node function call. Sort of a misnomer, original intent was to
  make it easy to wrap node library/module calls into Promises, but
  works for any async call
• fcall: turns functions synchronously returning a value into a Promise,
• You can make it so it’s Promises all the way down (at least until you hit
  the turtles)
Q.defer: Interject Promise Support
•    Use when you have to intermingle other logic inside callback work
function getLocation() {
  var deferred = Q.defer();

    console.log("Calling getCurrentPosition");
    navigator.geolocation.getCurrentPosition(function(position) {
        deferred.resolve(position);
        console.log("getCurrentPosition resolved");
      }, function(error){
        deferred.reject(error);
        console.log("getCurrentPosition errored");
      });

         return deferred.promise;
    };
Q.when: Wrapping Other
             Libraries’ Promises
•   From the Q documentation: “Not all promise libraries make the same
    guarantees as Q and certainly don’t provide all of the same methods.
    Most libraries only provide a partially functional then method.”

return Q.when($.ajax(...))
.then(function () {
});
Control Flow and Error Handling
Simple Flow
•   Use then/fail (and .done() to avoid swallowing unhandled exceptions)

•   You can chain then calls

Q.fcall(step1) // This returns a Promise obj
.then(step2)
.then(step3)
.then(step4)
.then(function (value4) {
    // Do something with value4
}, function (error) {
    // Handle any error from step1 through step4
})
.done();   // from https://github.com/kriskowal/q
More Complex Handling
•   Q.reduce(): Chain indeterminate-length sequential chains

•   all(): Turn multiple Promises in an array into a single Promise. Fails at
    the first failure from any Promise, returning that failure

•   allResolved(): Turn multiple Promises in an array into a single Promise.
    Succeeds when all Promises complete, resolved or failed, and resolves
    with the array of Promises
Testing
Mocha + Chai + Chai-as-Promised
•   Mocha: http://visionmedia.github.com/mocha/ -- unit testing framework

•   Chai: http://chaijs.com/ -- BDD add-on for Mocha

•   Chai-as-promised: https://github.com/domenic/chai-as-promised --
    Promises-enables Chai/Mocha
Mocha + Chai + Chai-as-Promised
•   Adds testability methods to promises supporting BDD

•   Note the use of done, which signals the async part of mocha
it('Should error on short barcode format', function(done){
  var promise = lookupBarcode(lookupData.shortGtinData.gtin);
  promise.should.be.rejected.and.notify(done);
});
Resources
•   Q javascript library: https://github.com/kriskowal/q

•   Q documentation: http://documentup.com/kriskowal/q/
Thank you. Questions?

Mais conteúdo relacionado

Mais procurados

Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
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 jsThomas Roch
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript PromisesTomasz Bak
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS PromisesAsa Kusuma
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promisesTorontoNodeJS
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promiseeslam_me
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript PromisesAsa Kusuma
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was BornDomenic Denicola
 
Intro to React
Intro to ReactIntro to React
Intro to ReactTroy Miles
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3Luciano Mammino
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script PromiseAlok Guha
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsKonrad Malawski
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...andreaslubbe
 
Middy.js - A powerful Node.js middleware framework for your lambdas​
Middy.js - A powerful Node.js middleware framework for your lambdas​ Middy.js - A powerful Node.js middleware framework for your lambdas​
Middy.js - A powerful Node.js middleware framework for your lambdas​ Luciano Mammino
 
Serverless, The Middy Way - Workshop
Serverless, The Middy Way - WorkshopServerless, The Middy Way - Workshop
Serverless, The Middy Way - WorkshopLuciano Mammino
 

Mais procurados (20)

Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
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
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
JavaScript Promise
JavaScript PromiseJavaScript Promise
JavaScript Promise
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
How to send gzipped requests with boto3
How to send gzipped requests with boto3How to send gzipped requests with boto3
How to send gzipped requests with boto3
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
 
JavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good PartsJavaOne 2013: Java 8 - The Good Parts
JavaOne 2013: Java 8 - The Good Parts
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
 
Middy.js - A powerful Node.js middleware framework for your lambdas​
Middy.js - A powerful Node.js middleware framework for your lambdas​ Middy.js - A powerful Node.js middleware framework for your lambdas​
Middy.js - A powerful Node.js middleware framework for your lambdas​
 
Serverless, The Middy Way - Workshop
Serverless, The Middy Way - WorkshopServerless, The Middy Way - Workshop
Serverless, The Middy Way - Workshop
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
 
Tech friday 22.01.2016
Tech friday 22.01.2016Tech friday 22.01.2016
Tech friday 22.01.2016
 

Destaque

Node.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideNode.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideMek Srunyu Stittri
 
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...Domenic Denicola
 
Tech Webinar: Advanced AngularJS, tecniche avanzate per padroneggiare il fram...
Tech Webinar: Advanced AngularJS, tecniche avanzate per padroneggiare il fram...Tech Webinar: Advanced AngularJS, tecniche avanzate per padroneggiare il fram...
Tech Webinar: Advanced AngularJS, tecniche avanzate per padroneggiare il fram...Codemotion
 
Guide to AngularJS Services - NOVA MEAN August 2014
Guide to AngularJS Services - NOVA MEAN August 2014Guide to AngularJS Services - NOVA MEAN August 2014
Guide to AngularJS Services - NOVA MEAN August 2014async_io
 
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its SuccessNOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Successasync_io
 
Using Jython To Prototype Mahout Code
Using Jython To Prototype Mahout CodeUsing Jython To Prototype Mahout Code
Using Jython To Prototype Mahout Codeasync_io
 
Building a Cauldron for Chef to Cook In
Building a Cauldron for Chef to Cook InBuilding a Cauldron for Chef to Cook In
Building a Cauldron for Chef to Cook Inasync_io
 
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!async_io
 
Design Patterns for Scalable Test Automation With Selenium & WebdriverIO
Design Patterns for Scalable Test Automation With Selenium & WebdriverIODesign Patterns for Scalable Test Automation With Selenium & WebdriverIO
Design Patterns for Scalable Test Automation With Selenium & WebdriverIOSauce Labs
 
Lessons Learned from Building a REST API on Google App Engine
Lessons Learned from Building a REST API on Google App EngineLessons Learned from Building a REST API on Google App Engine
Lessons Learned from Building a REST API on Google App Engineasync_io
 
Dcjq node.js presentation
Dcjq node.js presentationDcjq node.js presentation
Dcjq node.js presentationasync_io
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
Basic docker for developer
Basic docker for developerBasic docker for developer
Basic docker for developerWeerayut Hongsa
 

Destaque (15)

Node.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideNode.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java side
 
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...
 
Tech Webinar: Advanced AngularJS, tecniche avanzate per padroneggiare il fram...
Tech Webinar: Advanced AngularJS, tecniche avanzate per padroneggiare il fram...Tech Webinar: Advanced AngularJS, tecniche avanzate per padroneggiare il fram...
Tech Webinar: Advanced AngularJS, tecniche avanzate per padroneggiare il fram...
 
Guide to AngularJS Services - NOVA MEAN August 2014
Guide to AngularJS Services - NOVA MEAN August 2014Guide to AngularJS Services - NOVA MEAN August 2014
Guide to AngularJS Services - NOVA MEAN August 2014
 
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its SuccessNOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
NOVA MEAN - Why the M in MEAN is a Significant Contributor to Its Success
 
Using Jython To Prototype Mahout Code
Using Jython To Prototype Mahout CodeUsing Jython To Prototype Mahout Code
Using Jython To Prototype Mahout Code
 
Building a Cauldron for Chef to Cook In
Building a Cauldron for Chef to Cook InBuilding a Cauldron for Chef to Cook In
Building a Cauldron for Chef to Cook In
 
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
Using npm to Manage Your Projects for Fun and Profit - USEFUL INFO IN NOTES!
 
Design Patterns for Scalable Test Automation With Selenium & WebdriverIO
Design Patterns for Scalable Test Automation With Selenium & WebdriverIODesign Patterns for Scalable Test Automation With Selenium & WebdriverIO
Design Patterns for Scalable Test Automation With Selenium & WebdriverIO
 
Lessons Learned from Building a REST API on Google App Engine
Lessons Learned from Building a REST API on Google App EngineLessons Learned from Building a REST API on Google App Engine
Lessons Learned from Building a REST API on Google App Engine
 
Dcjq node.js presentation
Dcjq node.js presentationDcjq node.js presentation
Dcjq node.js presentation
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
QtQuick Day 2
QtQuick Day 2QtQuick Day 2
QtQuick Day 2
 
QtQuick Day 3
QtQuick Day 3QtQuick Day 3
QtQuick Day 3
 
Basic docker for developer
Basic docker for developerBasic docker for developer
Basic docker for developer
 

Semelhante a Javascript Promises and the Q library for asynchronous code

Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async futureslicejs
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
The State of Lightweight Threads for the JVM
The State of Lightweight Threads for the JVMThe State of Lightweight Threads for the JVM
The State of Lightweight Threads for the JVMVolkan Yazıcı
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
Scala, ECS, Docker: Delayed Execution @Coursera
Scala, ECS, Docker: Delayed Execution @CourseraScala, ECS, Docker: Delayed Execution @Coursera
Scala, ECS, Docker: Delayed Execution @CourseraC4Media
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011tobiascrawley
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraAllen Wirfs-Brock
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA PresentationRob Tweed
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisRuslan Shevchenko
 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsAyush Sharma
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Jalpesh Vadgama
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern偉格 高
 
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++PRINCE KUMAR
 

Semelhante a Javascript Promises and the Q library for asynchronous code (20)

Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
The State of Lightweight Threads for the JVM
The State of Lightweight Threads for the JVMThe State of Lightweight Threads for the JVM
The State of Lightweight Threads for the JVM
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Scala, ECS, Docker: Delayed Execution @Coursera
Scala, ECS, Docker: Delayed Execution @CourseraScala, ECS, Docker: Delayed Execution @Coursera
Scala, ECS, Docker: Delayed Execution @Coursera
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Advanced Java Testing
Advanced Java TestingAdvanced Java Testing
Advanced Java Testing
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern
 
Polymorphism Using C++
Polymorphism Using C++Polymorphism Using C++
Polymorphism Using C++
 

Último

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Javascript Promises and the Q library for asynchronous code

  • 1. Javascript Promises/Q library Jonathan Altman node.dc March 2013 @async_io http://async.io/
  • 2. What is a Promise? The simplest explanation: it is an easy way to avoid writing the Pyramid of Doom
  • 3. Pyramid of Doom step1(function (value1) { step2(value1, function(value2) { step3(value2, function(value3) { step4(value3, function(value4) { // Do something with value4 }); }); }); }); // from https://github.com/kriskowal/q
  • 4. Why Promises? What about? • async: http://github.com/caolan/async • step: https://github.com/creationix/step • flow-js: https://github.com/willconant/flow-js • ...you get the point
  • 5. Non-Promises Fix: async.series({ normalize: function(callback){ // Bodies removed for brevity } , compose: function(callback){ } , invert: function(callback){ } // A bunch more stuff killed } , function (err, results) { if (!err ) { err = new Error('Results did not contain a valid image buffer') } else { callback(err, results.imageBuffer); } } }); //https://github.com/jonathana/heatNode/blob/master/lib/imageGen/generateimages.js
  • 6. Is That Not Good Enough? var later = Q.nfcall(nodedc.wait_a_few_slides); // or: we’ll come back to it
  • 7. Promises: Longer Explanation “A Promise is an object representation of an event. In the course of its life, a Promise goes from a pending state, when it’s called, to a resolved or rejected state, when it’s been completed, or it could also stay pending forever and is never resolved.” http://flaviocopes.com/deferred-and-promises-in-javascript/
  • 8. Say What? • Promises take a call to an asynchronous function and wrap it with an object whose methods proxy when the wrapped function either completes or errors • A good Promise library also provides a set of control methods on that object wrapper to handle composition of multiple Promise-ified asynchronous method calls • Promises use the best qualities of an object--encapsulation of state--to track the state of an asynchronous call
  • 9. Promises provide a solid abstraction for representing the state of an asynchronous call and writing flow of control code based on that state
  • 10. Pyramid of Doom Again step1(function (value1) { step2(value1, function(value2) { step3(value2, function(value3) { step4(value3, function(value4) { // Do something with value4 }); }); }); }); // from https://github.com/kriskowal/q
  • 11. Pyramid of Doom on Promises Q.fcall(step1) // This returns a Promise obj .then(step2) .then(step3) .then(step4) .then(function (value4) { // Do something with value4 }, function (error) { // Handle any error from step1 through step4 }) .done(); // from https://github.com/kriskowal/q
  • 12. Again, Why Promises? • It’s a spec: http://wiki.commonjs.org/wiki/Promises/A • Generally supported by a bunch of libs both browser and server-side: • jQuery (sort of, supposedly doesn’t fully work like Promises/A) • AngularJS • Q library (https://github.com/kriskowal/q) • Provides separation of concerns between wrapping and flow of control handling of deferred activities
  • 13. later.then(function(){ Provides separation of concerns between wrapping and flow of control handling of deferred activities // that separation is the key });
  • 14. Promises can (mostly) be shared across libraries
  • 15. Sharing • Many libraries can exchange Promise objects • AngularJS’ Promise API is explicitly based off a subset of Q. If Q is loads first, AngularJS just uses that • jQuery’s promises can be consumed by Q, with some adaptations
  • 16. So Why Q? • Q consumes Promises from most other libraries • Pure Javascript library • Can be used both client-side (browser or e.g. Phonegap) and server-side (npm install q, but you’re using package.json, right?) • Provides utilities to make it easy to write Promise-based code or wrap non-Promise- based functions • Provides a library of methods to build control flow around Promise results and errors • Small (enough?): ~1400 SLOC, ~ 8.5kb minified
  • 18. Q.fcall/nfcall: Wrap an Async method with a Promise function writeError(errMessage) { return Q.nfcall(fs.writeFile, "errors.log", errMessage); } • nfcall: node function call. Sort of a misnomer, original intent was to make it easy to wrap node library/module calls into Promises, but works for any async call • fcall: turns functions synchronously returning a value into a Promise, • You can make it so it’s Promises all the way down (at least until you hit the turtles)
  • 19. Q.defer: Interject Promise Support • Use when you have to intermingle other logic inside callback work function getLocation() { var deferred = Q.defer(); console.log("Calling getCurrentPosition"); navigator.geolocation.getCurrentPosition(function(position) { deferred.resolve(position); console.log("getCurrentPosition resolved"); }, function(error){ deferred.reject(error); console.log("getCurrentPosition errored"); }); return deferred.promise; };
  • 20. Q.when: Wrapping Other Libraries’ Promises • From the Q documentation: “Not all promise libraries make the same guarantees as Q and certainly don’t provide all of the same methods. Most libraries only provide a partially functional then method.” return Q.when($.ajax(...)) .then(function () { });
  • 21. Control Flow and Error Handling
  • 22. Simple Flow • Use then/fail (and .done() to avoid swallowing unhandled exceptions) • You can chain then calls Q.fcall(step1) // This returns a Promise obj .then(step2) .then(step3) .then(step4) .then(function (value4) { // Do something with value4 }, function (error) { // Handle any error from step1 through step4 }) .done(); // from https://github.com/kriskowal/q
  • 23. More Complex Handling • Q.reduce(): Chain indeterminate-length sequential chains • all(): Turn multiple Promises in an array into a single Promise. Fails at the first failure from any Promise, returning that failure • allResolved(): Turn multiple Promises in an array into a single Promise. Succeeds when all Promises complete, resolved or failed, and resolves with the array of Promises
  • 25. Mocha + Chai + Chai-as-Promised • Mocha: http://visionmedia.github.com/mocha/ -- unit testing framework • Chai: http://chaijs.com/ -- BDD add-on for Mocha • Chai-as-promised: https://github.com/domenic/chai-as-promised -- Promises-enables Chai/Mocha
  • 26. Mocha + Chai + Chai-as-Promised • Adds testability methods to promises supporting BDD • Note the use of done, which signals the async part of mocha it('Should error on short barcode format', function(done){ var promise = lookupBarcode(lookupData.shortGtinData.gtin); promise.should.be.rejected.and.notify(done); });
  • 27. Resources • Q javascript library: https://github.com/kriskowal/q • Q documentation: http://documentup.com/kriskowal/q/