SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

Денис Лебедев-Управление зависимостями с помощью CocoaPods
Денис Лебедев-Управление зависимостями с помощью CocoaPodsДенис Лебедев-Управление зависимостями с помощью CocoaPods
Денис Лебедев-Управление зависимостями с помощью CocoaPods
UA Mobile
 
Database honeypot by design
Database honeypot by designDatabase honeypot by design
Database honeypot by design
qqlan
 
Rubyで簡単にremote access apiを実行する
Rubyで簡単にremote access apiを実行するRubyで簡単にremote access apiを実行する
Rubyで簡単にremote access apiを実行する
Maki Toshio
 

La actualidad más candente (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
 

Destacado

Week 1 lecture - The Sacred Beginnings
Week 1 lecture - The Sacred BeginningsWeek 1 lecture - The Sacred Beginnings
Week 1 lecture - The Sacred Beginnings
JenSantry
 
Louis braille topic
Louis braille topic Louis braille topic
Louis braille topic
md shadab
 
Quadri elettrici in bassa tensione
Quadri elettrici in bassa tensioneQuadri elettrici in bassa tensione
Quadri elettrici in bassa tensione
ANIE Energia
 
Proposal pendirian koperasi konsumsi
Proposal pendirian koperasi konsumsiProposal pendirian koperasi konsumsi
Proposal pendirian koperasi konsumsi
innaannisa
 
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
doina_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 Lunches
JenSantry
 
Varnita-Bender Community Project
Varnita-Bender Community ProjectVarnita-Bender Community Project
Varnita-Bender Community Project
doina_morari
 

Destacado (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
 

Similar a JavaScript tips - Unnest callbacks and method declarations

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
Konstantin Sorokin
 

Similar a 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
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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
 

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