SlideShare une entreprise Scribd logo
1  sur  9
JavaScript Tips

Unnest Callbacks and Method Declarations
to improve readability and performance

Akbar S. Ahmed
Founder, Exponential.io – Build better apps faster with less effort.
Twitter: @exponential_io
Web: www.Exponential.io
Agenda
• Callbacks
– Nested
– Unnested

• Method Declarations
– Nested
– Unnested

Git: https://github.com/akbarahmed/unnest-callbacks-in-javascript
Response time is 290 ms.

Nested Callback
#!/usr/bin/env node
var fs = require('fs');
fs.readFile('./file1.txt', function (err, file1Contents) {
if (err) throw err;
fs.readFile('./file2.txt', function (err, file2Contents) {
if (err) throw err;

var file3Contents = [file1Contents, file2Contents].join('');
fs.writeFile('file3.txt', file3Contents, function (err) {
if (err) throw err;
console.log('Concatenated file1.txt and file2.txt into file3.txt.');
});

});
});
Response time is 114 ms.

Unnested Callback: Properties
#!/usr/bin/env node
var fs = require('fs');
fs.readFile('./file1.txt', readFile1);
function readFile1(err, data) {
if (err) throw err;
writeFile3.file1Contents = data;
fs.readFile('./file2.txt', readFile2);
}
function readFile2(err, data) {
if (err) throw err;
writeFile3.file2Contents = data;
var file3Contents = [writeFile3.file1Contents, writeFile3.file2Contents].join('');
fs.writeFile('file3.txt', file3Contents, writeFile3);
}
…
Response time is 114 ms.

Unnested Callback: File Globals
#!/usr/bin/env node
var fs = require('fs');
var file1Contents, file2Contents, file3Contents;
fs.readFile('./file1.txt', readFile1);
function readFile1(err, data) {
if (err) throw err;
file1Contents = data;
fs.readFile('./file2.txt', readFile2);
}
function readFile2(err, data) {
if (err) throw err;
file2Contents = data;
file3Contents = [file1Contents, file2Contents].join('');
fs.writeFile('file3.txt', file3Contents, writeFile3);
}
…
Unnested Callback Benefits
•
•
•
•

Code is easier to read
Flow of code is clear
Better performance
Named functions yield better error messages
Response time is 280 ns (that’s nanoseconds).

Nested Method Declaration
#!/usr/bin/env node
function Cat(name) {
this.getName = function () {
return name;
};
this.setName = function (n) {
name = n;
};
}
var meows = new Cat('meows');
console.log('I am a cat named ' + meows.getName());
Response time is 7 ns (that’s nanoseconds).

Unnested Method Declaration
#!/usr/bin/env node
function Cat(name) {
this._name = name;
}
Cat.prototype.getName = function () {
return this._name;
};
Cat.prototype.setName = function (n) {
this._name = n;
};
var meows = new Cat('meows');
console.log('I am a cat named ' + meows.getName());
npm install -g exponential
• Exponential.io alphas recently released
• Your input would be greatly appreciated
• Email: akbar@exponential.io
• Twitter: @exponential_io

Contenu connexe

Tendances

Ansibleではじめるサーバー・ネットワークの自動化(2019/02版)
Ansibleではじめるサーバー・ネットワークの自動化(2019/02版)Ansibleではじめるサーバー・ネットワークの自動化(2019/02版)
Ansibleではじめるサーバー・ネットワークの自動化(2019/02版)akira6592
 
OWASP Nagpur Meet #3 Android RE
OWASP Nagpur Meet #3 Android REOWASP Nagpur Meet #3 Android RE
OWASP Nagpur Meet #3 Android REOWASP Nagpur
 
Linux commands-effectiveness
Linux commands-effectivenessLinux commands-effectiveness
Linux commands-effectivenessRubizza
 
Денис Лебедев-Управление зависимостями с помощью CocoaPods
Денис Лебедев-Управление зависимостями с помощью CocoaPodsДенис Лебедев-Управление зависимостями с помощью CocoaPods
Денис Лебедев-Управление зависимостями с помощью CocoaPodsUA Mobile
 
Development of Ansible modules
Development of Ansible modulesDevelopment of Ansible modules
Development of Ansible modulesjtyr
 
Learned lessons in a real world project
Learned lessons in a real world projectLearned lessons in a real world project
Learned lessons in a real world projectCodium
 
Distributed tracing for Node.js
Distributed tracing for Node.jsDistributed tracing for Node.js
Distributed tracing for Node.jsNikolay Stoitsev
 
AnsibleではじめるNW設定の自動化について - Cisco(VIRL)編 -
AnsibleではじめるNW設定の自動化について - Cisco(VIRL)編 -AnsibleではじめるNW設定の自動化について - Cisco(VIRL)編 -
AnsibleではじめるNW設定の自動化について - Cisco(VIRL)編 -Yasuyuki Sugai
 
Gnu build system
Gnu build systemGnu build system
Gnu build system家榮 吳
 
Python eggs (RO)
Python eggs (RO)Python eggs (RO)
Python eggs (RO)Alin Voinea
 
Database honeypot by design
Database honeypot by designDatabase honeypot by design
Database honeypot by designqqlan
 
Rubyで簡単にremote access apiを実行する
Rubyで簡単にremote access apiを実行するRubyで簡単にremote access apiを実行する
Rubyで簡単にremote access apiを実行するMaki Toshio
 
とりあえずはじめるChatOps
とりあえずはじめるChatOpsとりあえずはじめるChatOps
とりあえずはじめるChatOps正貴 小川
 

Tendances (20)

Codemotion 2015
Codemotion 2015Codemotion 2015
Codemotion 2015
 
Ansibleではじめるサーバー・ネットワークの自動化(2019/02版)
Ansibleではじめるサーバー・ネットワークの自動化(2019/02版)Ansibleではじめるサーバー・ネットワークの自動化(2019/02版)
Ansibleではじめるサーバー・ネットワークの自動化(2019/02版)
 
Django Deployment-in-AWS
Django Deployment-in-AWSDjango Deployment-in-AWS
Django Deployment-in-AWS
 
OWASP Nagpur Meet #3 Android RE
OWASP Nagpur Meet #3 Android REOWASP Nagpur Meet #3 Android RE
OWASP Nagpur Meet #3 Android RE
 
Linux commands-effectiveness
Linux commands-effectivenessLinux commands-effectiveness
Linux commands-effectiveness
 
Денис Лебедев-Управление зависимостями с помощью CocoaPods
Денис Лебедев-Управление зависимостями с помощью CocoaPodsДенис Лебедев-Управление зависимостями с помощью CocoaPods
Денис Лебедев-Управление зависимостями с помощью CocoaPods
 
Development of Ansible modules
Development of Ansible modulesDevelopment of Ansible modules
Development of Ansible modules
 
Learned lessons in a real world project
Learned lessons in a real world projectLearned lessons in a real world project
Learned lessons in a real world project
 
Distributed tracing for Node.js
Distributed tracing for Node.jsDistributed tracing for Node.js
Distributed tracing for Node.js
 
Hello git
Hello git Hello git
Hello git
 
AnsibleではじめるNW設定の自動化について - Cisco(VIRL)編 -
AnsibleではじめるNW設定の自動化について - Cisco(VIRL)編 -AnsibleではじめるNW設定の自動化について - Cisco(VIRL)編 -
AnsibleではじめるNW設定の自動化について - Cisco(VIRL)編 -
 
Amazon Ec2
Amazon Ec2Amazon Ec2
Amazon Ec2
 
Gnu build system
Gnu build systemGnu build system
Gnu build system
 
Modern Perl Toolchain
Modern Perl ToolchainModern Perl Toolchain
Modern Perl Toolchain
 
Python eggs (RO)
Python eggs (RO)Python eggs (RO)
Python eggs (RO)
 
Database honeypot by design
Database honeypot by designDatabase honeypot by design
Database honeypot by design
 
Rubyで簡単にremote access apiを実行する
Rubyで簡単にremote access apiを実行するRubyで簡単にremote access apiを実行する
Rubyで簡単にremote access apiを実行する
 
Docker Workshop L2
Docker Workshop L2Docker Workshop L2
Docker Workshop L2
 
とりあえずはじめるChatOps
とりあえずはじめるChatOpsとりあえずはじめるChatOps
とりあえずはじめるChatOps
 
4. copy2 in Laravel
4. copy2 in Laravel4. copy2 in Laravel
4. copy2 in Laravel
 

En vedette

BEAUTIFUL QUOTES
BEAUTIFUL QUOTESBEAUTIFUL QUOTES
BEAUTIFUL QUOTESminkevi
 
Week 1 lecture - The Sacred Beginnings
Week 1 lecture - The Sacred BeginningsWeek 1 lecture - The Sacred Beginnings
Week 1 lecture - The Sacred BeginningsJenSantry
 
Презентация "Экологические проблемы микрорайона"
Презентация "Экологические проблемы микрорайона"Презентация "Экологические проблемы микрорайона"
Презентация "Экологические проблемы микрорайона"KuklinaGL
 
Louis braille topic
Louis braille topic Louis braille topic
Louis braille topic md shadab
 
AGICI - Benefici recuperi termici
AGICI - Benefici recuperi termiciAGICI - Benefici recuperi termici
AGICI - Benefici recuperi termiciANIE Energia
 
Quadri elettrici in bassa tensione
Quadri elettrici in bassa tensioneQuadri elettrici in bassa tensione
Quadri elettrici in bassa tensioneANIE Energia
 
EDF FENICE - Efficienza Energetica nell'automotive
EDF FENICE - Efficienza Energetica nell'automotiveEDF FENICE - Efficienza Energetica nell'automotive
EDF FENICE - Efficienza Energetica nell'automotiveANIE Energia
 
Proposal pendirian koperasi konsumsi
Proposal pendirian koperasi konsumsiProposal pendirian koperasi konsumsi
Proposal pendirian koperasi konsumsiinnaannisa
 
Access microscholarship program, moldova april-september, 2013 actvities
Access microscholarship program, moldova  april-september, 2013 actvitiesAccess microscholarship program, moldova  april-september, 2013 actvities
Access microscholarship program, moldova april-september, 2013 actvitiesdoina_morari
 
19151 project ,,a_new_school_schedule’’
19151 project ,,a_new_school_schedule’’19151 project ,,a_new_school_schedule’’
19151 project ,,a_new_school_schedule’’doina_morari
 
Week 4 - School Lunches
Week 4 - School LunchesWeek 4 - School Lunches
Week 4 - School LunchesJenSantry
 
Varnita-Bender Community Project
Varnita-Bender Community ProjectVarnita-Bender Community Project
Varnita-Bender Community Projectdoina_morari
 

En vedette (16)

Odesk html set 4
Odesk html set 4Odesk html set 4
Odesk html set 4
 
BEAUTIFUL QUOTES
BEAUTIFUL QUOTESBEAUTIFUL QUOTES
BEAUTIFUL QUOTES
 
Week 1 lecture - The Sacred Beginnings
Week 1 lecture - The Sacred BeginningsWeek 1 lecture - The Sacred Beginnings
Week 1 lecture - The Sacred Beginnings
 
Hipster
Hipster Hipster
Hipster
 
Презентация "Экологические проблемы микрорайона"
Презентация "Экологические проблемы микрорайона"Презентация "Экологические проблемы микрорайона"
Презентация "Экологические проблемы микрорайона"
 
Louis braille topic
Louis braille topic Louis braille topic
Louis braille topic
 
AGICI - Benefici recuperi termici
AGICI - Benefici recuperi termiciAGICI - Benefici recuperi termici
AGICI - Benefici recuperi termici
 
Quadri elettrici in bassa tensione
Quadri elettrici in bassa tensioneQuadri elettrici in bassa tensione
Quadri elettrici in bassa tensione
 
Shot types
Shot typesShot types
Shot types
 
EDF FENICE - Efficienza Energetica nell'automotive
EDF FENICE - Efficienza Energetica nell'automotiveEDF FENICE - Efficienza Energetica nell'automotive
EDF FENICE - Efficienza Energetica nell'automotive
 
Proposal pendirian koperasi konsumsi
Proposal pendirian koperasi konsumsiProposal pendirian koperasi konsumsi
Proposal pendirian koperasi konsumsi
 
Access microscholarship program, moldova april-september, 2013 actvities
Access microscholarship program, moldova  april-september, 2013 actvitiesAccess microscholarship program, moldova  april-september, 2013 actvities
Access microscholarship program, moldova april-september, 2013 actvities
 
19151 project ,,a_new_school_schedule’’
19151 project ,,a_new_school_schedule’’19151 project ,,a_new_school_schedule’’
19151 project ,,a_new_school_schedule’’
 
Week 4 - School Lunches
Week 4 - School LunchesWeek 4 - School Lunches
Week 4 - School Lunches
 
Mix Me
Mix MeMix Me
Mix Me
 
Varnita-Bender Community Project
Varnita-Bender Community ProjectVarnita-Bender Community Project
Varnita-Bender Community Project
 

Similaire à JavaScript tips - Unnest callbacks and method declarations

Echtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQLEchtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQLMoritz Flucht
 
Azure Functions 2.0 Deep Dive - デベロッパーのための最新開発ガイド
Azure Functions 2.0 Deep Dive - デベロッパーのための最新開発ガイドAzure Functions 2.0 Deep Dive - デベロッパーのための最新開発ガイド
Azure Functions 2.0 Deep Dive - デベロッパーのための最新開発ガイドYoichi Kawasaki
 
Kostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program DevelopmenKostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program DevelopmenKonstantin Sorokin
 
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiGrâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiJérémy Derussé
 
Writing Commits for You, Your Friends, and Your Future Self
Writing Commits for You, Your Friends, and Your Future SelfWriting Commits for You, Your Friends, and Your Future Self
Writing Commits for You, Your Friends, and Your Future SelfAll Things Open
 
Microservices, Containers, and Machine Learning
Microservices, Containers, and Machine LearningMicroservices, Containers, and Machine Learning
Microservices, Containers, and Machine LearningPaco Nathan
 
[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화Henry Jeong
 
[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화NAVER D2
 
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...Provectus
 
Tdc 2013 - Ecossistema Ruby
Tdc 2013 - Ecossistema RubyTdc 2013 - Ecossistema Ruby
Tdc 2013 - Ecossistema RubyFabio Akita
 
Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Scott Keck-Warren
 
Regex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language InsteadRegex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language InsteadAll Things Open
 
Embulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loaderEmbulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loaderSadayuki Furuhashi
 
How to Design a Great API (using flask) [ploneconf2017]
How to Design a Great API (using flask) [ploneconf2017]How to Design a Great API (using flask) [ploneconf2017]
How to Design a Great API (using flask) [ploneconf2017]Devon Bernard
 
The-Power-Of-Recon (1)-poerfulo.pptx.pdf
The-Power-Of-Recon (1)-poerfulo.pptx.pdfThe-Power-Of-Recon (1)-poerfulo.pptx.pdf
The-Power-Of-Recon (1)-poerfulo.pptx.pdfnezidsilva
 
Apache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos LinardosApache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos LinardosEuangelos Linardos
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
DevOpsDays InSpec Workshop
DevOpsDays InSpec WorkshopDevOpsDays InSpec Workshop
DevOpsDays InSpec WorkshopMandi Walls
 
AWS ElasticBeanstalk Advanced configuration
AWS ElasticBeanstalk Advanced configurationAWS ElasticBeanstalk Advanced configuration
AWS ElasticBeanstalk Advanced configurationLionel LONKAP TSAMBA
 

Similaire à JavaScript tips - Unnest callbacks and method declarations (20)

Echtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQLEchtzeitapplikationen mit Elixir und GraphQL
Echtzeitapplikationen mit Elixir und GraphQL
 
Azure Functions 2.0 Deep Dive - デベロッパーのための最新開発ガイド
Azure Functions 2.0 Deep Dive - デベロッパーのための最新開発ガイドAzure Functions 2.0 Deep Dive - デベロッパーのための最新開発ガイド
Azure Functions 2.0 Deep Dive - デベロッパーのための最新開発ガイド
 
Kostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program DevelopmenKostis Sagonas: Cool Tools for Modern Erlang Program Developmen
Kostis Sagonas: Cool Tools for Modern Erlang Program Developmen
 
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiGrâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
 
Writing Commits for You, Your Friends, and Your Future Self
Writing Commits for You, Your Friends, and Your Future SelfWriting Commits for You, Your Friends, and Your Future Self
Writing Commits for You, Your Friends, and Your Future Self
 
Microservices, Containers, and Machine Learning
Microservices, Containers, and Machine LearningMicroservices, Containers, and Machine Learning
Microservices, Containers, and Machine Learning
 
[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화
 
[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화
 
Mist - Serverless proxy to Apache Spark
Mist - Serverless proxy to Apache SparkMist - Serverless proxy to Apache Spark
Mist - Serverless proxy to Apache Spark
 
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
 
Tdc 2013 - Ecossistema Ruby
Tdc 2013 - Ecossistema RubyTdc 2013 - Ecossistema Ruby
Tdc 2013 - Ecossistema Ruby
 
Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023Static Code Analysis PHP[tek] 2023
Static Code Analysis PHP[tek] 2023
 
Regex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language InsteadRegex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language Instead
 
Embulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loaderEmbulk, an open-source plugin-based parallel bulk data loader
Embulk, an open-source plugin-based parallel bulk data loader
 
How to Design a Great API (using flask) [ploneconf2017]
How to Design a Great API (using flask) [ploneconf2017]How to Design a Great API (using flask) [ploneconf2017]
How to Design a Great API (using flask) [ploneconf2017]
 
The-Power-Of-Recon (1)-poerfulo.pptx.pdf
The-Power-Of-Recon (1)-poerfulo.pptx.pdfThe-Power-Of-Recon (1)-poerfulo.pptx.pdf
The-Power-Of-Recon (1)-poerfulo.pptx.pdf
 
Apache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos LinardosApache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos Linardos
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
DevOpsDays InSpec Workshop
DevOpsDays InSpec WorkshopDevOpsDays InSpec Workshop
DevOpsDays InSpec Workshop
 
AWS ElasticBeanstalk Advanced configuration
AWS ElasticBeanstalk Advanced configurationAWS ElasticBeanstalk Advanced configuration
AWS ElasticBeanstalk Advanced configuration
 

Dernier

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
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
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Dernier (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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...
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

JavaScript tips - Unnest callbacks and method declarations

  • 1. JavaScript Tips Unnest Callbacks and Method Declarations to improve readability and performance Akbar S. Ahmed Founder, Exponential.io – Build better apps faster with less effort. Twitter: @exponential_io Web: www.Exponential.io
  • 2. Agenda • Callbacks – Nested – Unnested • Method Declarations – Nested – Unnested Git: https://github.com/akbarahmed/unnest-callbacks-in-javascript
  • 3. Response time is 290 ms. Nested Callback #!/usr/bin/env node var fs = require('fs'); fs.readFile('./file1.txt', function (err, file1Contents) { if (err) throw err; fs.readFile('./file2.txt', function (err, file2Contents) { if (err) throw err; var file3Contents = [file1Contents, file2Contents].join(''); fs.writeFile('file3.txt', file3Contents, function (err) { if (err) throw err; console.log('Concatenated file1.txt and file2.txt into file3.txt.'); }); }); });
  • 4. Response time is 114 ms. Unnested Callback: Properties #!/usr/bin/env node var fs = require('fs'); fs.readFile('./file1.txt', readFile1); function readFile1(err, data) { if (err) throw err; writeFile3.file1Contents = data; fs.readFile('./file2.txt', readFile2); } function readFile2(err, data) { if (err) throw err; writeFile3.file2Contents = data; var file3Contents = [writeFile3.file1Contents, writeFile3.file2Contents].join(''); fs.writeFile('file3.txt', file3Contents, writeFile3); } …
  • 5. Response time is 114 ms. Unnested Callback: File Globals #!/usr/bin/env node var fs = require('fs'); var file1Contents, file2Contents, file3Contents; fs.readFile('./file1.txt', readFile1); function readFile1(err, data) { if (err) throw err; file1Contents = data; fs.readFile('./file2.txt', readFile2); } function readFile2(err, data) { if (err) throw err; file2Contents = data; file3Contents = [file1Contents, file2Contents].join(''); fs.writeFile('file3.txt', file3Contents, writeFile3); } …
  • 6. Unnested Callback Benefits • • • • Code is easier to read Flow of code is clear Better performance Named functions yield better error messages
  • 7. Response time is 280 ns (that’s nanoseconds). Nested Method Declaration #!/usr/bin/env node function Cat(name) { this.getName = function () { return name; }; this.setName = function (n) { name = n; }; } var meows = new Cat('meows'); console.log('I am a cat named ' + meows.getName());
  • 8. Response time is 7 ns (that’s nanoseconds). Unnested Method Declaration #!/usr/bin/env node function Cat(name) { this._name = name; } Cat.prototype.getName = function () { return this._name; }; Cat.prototype.setName = function (n) { this._name = n; }; var meows = new Cat('meows'); console.log('I am a cat named ' + meows.getName());
  • 9. npm install -g exponential • Exponential.io alphas recently released • Your input would be greatly appreciated • Email: akbar@exponential.io • Twitter: @exponential_io