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

Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandIES VE
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
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...FIDO Alliance
 
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.pdfFIDO Alliance
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptxFIDO Alliance
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?Mark Billinghurst
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Paige Cruz
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Patrick Viafore
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfFIDO Alliance
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...ScyllaDB
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfFIDO Alliance
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdfMuhammad Subhan
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentationyogeshlabana357357
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceSamy Fodil
 
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!.pdfSrushith Repakula
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 

Dernier (20)

Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
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
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
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
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 

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