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

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 

Último (20)

ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
THE BEST IPTV in GERMANY for 2024: IPTVreel
THE BEST IPTV in  GERMANY for 2024: IPTVreelTHE BEST IPTV in  GERMANY for 2024: IPTVreel
THE BEST IPTV in GERMANY for 2024: IPTVreel
 

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