SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Async History
-Nishchit D.

When you execute something synchronously, you wait for it to
finish before moving on to another task.
When you execute something asynchronously, you can move on
to another task before it finishes.
function Task(){



setTimeout(function () {



console.log("I'm done after 2 seconds")

}, 2000)



console.log("I'll come first");

}





Task()

// I'll come first

// I'm done after 2 seconds
Asynchronous ?
Sync vs Async
If your are dependent on something and It’s
taking time, You’ll be kick off.
function Task(addNum){



var total = Database.query()
// Takes 50ms
var result = total + addNum;



console.log(result);

}





Task(10) // Fires error
Problem
If the second task is dependent on the first
task, but the first task taking some time.
Then the second task will not return accurate
output.
var num = 0;

function First(){



setTimeout(function () {

num = 10;

}, 2000)

}



function Second(){



First();



return num % 2; //0

}
Problem
Finally
Anything in the code which is taking time will leads to
Asynchronous.
Even if it takes one ms.
Async Examples
1. DOM Event

2.Alert/Prompt
3. Database Query

4.APIs

5. setTimeout

6. setInterval

What to do?
What to do for handle Async tasks?

Implement something 

which can gives you the promise 

that the dependency 

task will get resolved or rejected 

properly before dependentTask start.

Async History
The Past Callback
The Present Promise
The Future Async/Await

Callback
A callback is a function which will passed as
argument to another function.
A callback function is executed after the current
effect is finished.
$("button").click(function(){


$("p").hide(1000);

alert("The paragraph is now hidden");

});
$("button").click(ImCallback);
function ImCallback(){



console.log("I’ll print after you click");

}
Callback looks like
function FastTask(cb) {



setTimeout(function () {



cb(null, 1)

}, 500)

}



function SlowTask(cb) {



setTimeout(function () {



cb(null, 2)

}, 1000)

}



function ErrorTask(cb) {



setTimeout(function () {

cb(new Error('Custom Error'))

}, 1000)

}



function ImCallback(err, result) {



console.log(err, result)

}
FastTask(ImCallback) // 0.5 sec

SlowTask(ImCallback) // 1 sec 

ErrorTask(ImCallback) // fire error
Standard Callback has two arguments
1. Error
2. result
callback(err, result)

Callback problem
GetUser(function(user){
GetProfile(user, function(profile){
GetAccount(profile, function(acc){
GetReport(acc, function(report){
SendStatistics(report, function(e){
...
});
});
});
});
});
The callbacks are good for handle the Async
functions.
But never use the nested callback approach for
handling asynchronous NodeJS operations
Callback Utility with async
Async is a utility module which provides
straight-forward, powerful functions for
working with asynchronous JavaScript.
npm install --save async
https://caolan.github.io/async/
async.waterfall(
[ GetUser,
GetProfile,
GetAccount,
GetReport,
SendStatistics ], function(){

console.log('done')

})
//parallel
async.parallel([FastTask, SlowTask], function(err, result){

console.log(err, 'done')

})
//series
async.series([FastTask, SlowTask], function(err, result){

console.log(err, 'done')

})
Promise
A promise represents the eventual result of an
asynchronous operation. It is a placeholder into
which the successful result value or reason for
failure will materialize.
A promise has 3 states.
Pending: You don’t know the status of the flight.
Resolved: The flight is on time.
Rejected: The flight is canceled due to some
reason.
Promise is accepted as ES6 native API.
Flight

.checkStatus()

.then(function (success) {


console.log('Flight is on time')

}, 

function (e) {


console.log('Flight is canceled due to ', e.message)

})

.catch(function (e) { //log


console.log('Flight is canceled due to ', e.message)

});
Promise Standards
1. Promise is always thenable.
Promise.then()

Flight.checkStatus().then()
2. Promise is chainable.

Promise
.then()
.then()...
.catch()
Flight.checkStatus()
.then(bookFlight)
.catch(handleError)

3. .then has 2 callback arguments
1. resolve & 2. reject
Promise.then(resolve, reject)
Promise.then(
function resolve(result) {



console.log(result)

},
function reject(err) {



console.log(err)

})
# If you don’t want to use reject as second argument, you can
use .catch
Promise.then(
function resolve(result) {

console.log(result)

})
.catch(
function reject(err) {

console.log(err)

})
Callback vs Promise
#PROMISE
GetUser()

.then(GetProfile)

.then(GetAccount)

.then(GetReport)

.then(SendStatistics)

.then(function (success) {

console.log(success)

})

.catch(function (e) {

console.error(e)

})
#CALLBACK
GetUser(function(user){
GetProfile(user, function(profile){
GetAccount(profile, function(acc){
GetReport(acc, function(report){
SendStatistics(report, function(e){
...
});
});
});
});
});
OR

#ASYNC
async.waterfall(
[ GetUser,
GetProfile,
GetAccount,
GetReport,
SendStatistics ], function(){

console.log('done')

})
Async & Await
Async/Await introduces in ES7
Async/Await is the next version of Promise.
The new async/await syntax allows you to still
use Promises, but it eliminates the need for
providing a callback to the chained then()
methods.
Async keyword defines an asynchronous
function.
Await indicates that you want to resolve the
Promise.
async function main() {
var users = await request
.get('api.com/users');
console.log('users', users);
}
main();
Error Handling
#PROMISE
GetUser()
.catch(function (e) {

console.error(e)

})

.then(function (success) {

console.log(success)

})

#CALLBACK
GetUser(function(err, user){
console.error(err)

});
#ASYNC/AWAIT


try {

var user = await GetUser(1)

console.log(user);

}

catch(err) {

console.log('Got an error:', err.message)

}

Callback vs Promise vs Async
#PROMISE
GetUser()

.then(GetProfile)

.then(GetAccount)

.then(GetReport)

.then(SendStatistics)

.then(function (success) {

console.log(success)

})

.catch(function (e) {

console.error(e)

})
#CALLBACK
GetUser(function(err, user){
GetProfile(user, function(err, profile){
GetAccount(profile, function(err, acc){
GetReport(acc, function(err, report){
SendStatistics(report, function(e){
...
});
});
});
});
});
#ASYNC/AWAIT


async function SendAsync() {



let user = await GetUser(1)

let profile = await GetProfile(user);

let account = await GetAccount(profile);

let report = await GetReport(account);



let send = SendStatistic(report);



console.log(send)

}
Thank you !!

Weitere ähnliche Inhalte

Was ist angesagt?

Explain it to Me Like I’m 5: Oauth2 and OpenID
Explain it to Me Like I’m 5: Oauth2 and OpenIDExplain it to Me Like I’m 5: Oauth2 and OpenID
Explain it to Me Like I’m 5: Oauth2 and OpenIDVMware Tanzu
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practicesfelixbillon
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional ExplainedVictor Rentea
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event EmittersTheCreativedev Blog
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses étatsJosé Paumard
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
Async-await best practices in 10 minutes
Async-await best practices in 10 minutesAsync-await best practices in 10 minutes
Async-await best practices in 10 minutesPaulo Morgado
 
Spring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'tsSpring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'tsJulien Wittouck
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hookPiyush Jamwal
 

Was ist angesagt? (20)

Explain it to Me Like I’m 5: Oauth2 and OpenID
Explain it to Me Like I’m 5: Oauth2 and OpenIDExplain it to Me Like I’m 5: Oauth2 and OpenID
Explain it to Me Like I’m 5: Oauth2 and OpenID
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional Explained
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Selenium IDE LOCATORS
Selenium IDE LOCATORSSelenium IDE LOCATORS
Selenium IDE LOCATORS
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
Introduction à React
Introduction à ReactIntroduction à React
Introduction à React
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses états
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Async-await best practices in 10 minutes
Async-await best practices in 10 minutesAsync-await best practices in 10 minutes
Async-await best practices in 10 minutes
 
React
React React
React
 
Spring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'tsSpring Boot & Containers - Do's & Don'ts
Spring Boot & Containers - Do's & Don'ts
 
Introduction to thymeleaf
Introduction to thymeleafIntroduction to thymeleaf
Introduction to thymeleaf
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
 

Ähnlich wie Async History - javascript

Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
Better react/redux apps using redux-saga
Better react/redux apps using redux-sagaBetter react/redux apps using redux-saga
Better react/redux apps using redux-sagaYounes (omar) Meliani
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous callsHuy Hoàng Phạm
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming heroThe Software House
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programmingMasters Academy
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejsLearningTech
 
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando CoroutinesTDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutinestdc-globalcode
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence Svekis ✔
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)Takayuki Goto
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingMichael Arenzon
 
Scheduling tasks the human way - Brad Wood - ITB2021
Scheduling tasks the human way -  Brad Wood - ITB2021Scheduling tasks the human way -  Brad Wood - ITB2021
Scheduling tasks the human way - Brad Wood - ITB2021Ortus Solutions, Corp
 
Programação assíncrona utilizando Coroutines
Programação assíncrona utilizando CoroutinesProgramação assíncrona utilizando Coroutines
Programação assíncrona utilizando CoroutinesDiego Gonçalves Santos
 

Ähnlich wie Async History - javascript (20)

Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
Node js
Node jsNode js
Node js
 
Better react/redux apps using redux-saga
Better react/redux apps using redux-sagaBetter react/redux apps using redux-saga
Better react/redux apps using redux-saga
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous calls
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programming
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando CoroutinesTDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
Async Web QA
Async Web QAAsync Web QA
Async Web QA
 
オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)オープンデータを使ったモバイルアプリ開発(応用編)
オープンデータを使ったモバイルアプリ開発(応用編)
 
Advanced patterns in asynchronous programming
Advanced patterns in asynchronous programmingAdvanced patterns in asynchronous programming
Advanced patterns in asynchronous programming
 
Scheduling tasks the human way - Brad Wood - ITB2021
Scheduling tasks the human way -  Brad Wood - ITB2021Scheduling tasks the human way -  Brad Wood - ITB2021
Scheduling tasks the human way - Brad Wood - ITB2021
 
Programação assíncrona utilizando Coroutines
Programação assíncrona utilizando CoroutinesProgramação assíncrona utilizando Coroutines
Programação assíncrona utilizando Coroutines
 

Kürzlich hochgeladen

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
 
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.pdfsudhanshuwaghmare1
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
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
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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
 
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
 
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 Takeoffsammart93
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 

Kürzlich hochgeladen (20)

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
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
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?
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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...
 
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
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

Async History - javascript

  • 2. When you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before it finishes. function Task(){
 
 setTimeout(function () {
 
 console.log("I'm done after 2 seconds")
 }, 2000)
 
 console.log("I'll come first");
 }
 
 
 Task()
 // I'll come first
 // I'm done after 2 seconds Asynchronous ?
  • 4. If your are dependent on something and It’s taking time, You’ll be kick off. function Task(addNum){
 
 var total = Database.query() // Takes 50ms var result = total + addNum;
 
 console.log(result);
 }
 
 
 Task(10) // Fires error Problem
  • 5. If the second task is dependent on the first task, but the first task taking some time. Then the second task will not return accurate output. var num = 0;
 function First(){
 
 setTimeout(function () {
 num = 10;
 }, 2000)
 }
 
 function Second(){
 
 First();
 
 return num % 2; //0
 } Problem
  • 6. Finally Anything in the code which is taking time will leads to Asynchronous. Even if it takes one ms.
  • 7. Async Examples 1. DOM Event
 2.Alert/Prompt 3. Database Query
 4.APIs
 5. setTimeout
 6. setInterval

  • 8. What to do? What to do for handle Async tasks?
 Implement something 
 which can gives you the promise 
 that the dependency 
 task will get resolved or rejected 
 properly before dependentTask start.

  • 9. Async History The Past Callback The Present Promise The Future Async/Await

  • 10. Callback A callback is a function which will passed as argument to another function. A callback function is executed after the current effect is finished. $("button").click(function(){ 
 $("p").hide(1000);
 alert("The paragraph is now hidden");
 }); $("button").click(ImCallback); function ImCallback(){
 
 console.log("I’ll print after you click");
 }
  • 11. Callback looks like function FastTask(cb) {
 
 setTimeout(function () {
 
 cb(null, 1)
 }, 500)
 }
 
 function SlowTask(cb) {
 
 setTimeout(function () {
 
 cb(null, 2)
 }, 1000)
 }
 
 function ErrorTask(cb) {
 
 setTimeout(function () {
 cb(new Error('Custom Error'))
 }, 1000)
 }
 
 function ImCallback(err, result) {
 
 console.log(err, result)
 } FastTask(ImCallback) // 0.5 sec
 SlowTask(ImCallback) // 1 sec 
 ErrorTask(ImCallback) // fire error Standard Callback has two arguments 1. Error 2. result callback(err, result)

  • 12. Callback problem GetUser(function(user){ GetProfile(user, function(profile){ GetAccount(profile, function(acc){ GetReport(acc, function(report){ SendStatistics(report, function(e){ ... }); }); }); }); }); The callbacks are good for handle the Async functions. But never use the nested callback approach for handling asynchronous NodeJS operations
  • 13. Callback Utility with async Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. npm install --save async https://caolan.github.io/async/ async.waterfall( [ GetUser, GetProfile, GetAccount, GetReport, SendStatistics ], function(){
 console.log('done')
 }) //parallel async.parallel([FastTask, SlowTask], function(err, result){
 console.log(err, 'done')
 }) //series async.series([FastTask, SlowTask], function(err, result){
 console.log(err, 'done')
 })
  • 14. Promise A promise represents the eventual result of an asynchronous operation. It is a placeholder into which the successful result value or reason for failure will materialize. A promise has 3 states. Pending: You don’t know the status of the flight. Resolved: The flight is on time. Rejected: The flight is canceled due to some reason. Promise is accepted as ES6 native API. Flight
 .checkStatus()
 .then(function (success) { 
 console.log('Flight is on time')
 }, 
 function (e) { 
 console.log('Flight is canceled due to ', e.message)
 })
 .catch(function (e) { //log 
 console.log('Flight is canceled due to ', e.message)
 });
  • 15. Promise Standards 1. Promise is always thenable. Promise.then()
 Flight.checkStatus().then() 2. Promise is chainable.
 Promise .then() .then()... .catch() Flight.checkStatus() .then(bookFlight) .catch(handleError)
 3. .then has 2 callback arguments 1. resolve & 2. reject Promise.then(resolve, reject) Promise.then( function resolve(result) {
 
 console.log(result)
 }, function reject(err) {
 
 console.log(err)
 }) # If you don’t want to use reject as second argument, you can use .catch Promise.then( function resolve(result) {
 console.log(result)
 }) .catch( function reject(err) {
 console.log(err)
 })
  • 16. Callback vs Promise #PROMISE GetUser()
 .then(GetProfile)
 .then(GetAccount)
 .then(GetReport)
 .then(SendStatistics)
 .then(function (success) {
 console.log(success)
 })
 .catch(function (e) {
 console.error(e)
 }) #CALLBACK GetUser(function(user){ GetProfile(user, function(profile){ GetAccount(profile, function(acc){ GetReport(acc, function(report){ SendStatistics(report, function(e){ ... }); }); }); }); }); OR
 #ASYNC async.waterfall( [ GetUser, GetProfile, GetAccount, GetReport, SendStatistics ], function(){
 console.log('done')
 })
  • 17. Async & Await Async/Await introduces in ES7 Async/Await is the next version of Promise. The new async/await syntax allows you to still use Promises, but it eliminates the need for providing a callback to the chained then() methods. Async keyword defines an asynchronous function. Await indicates that you want to resolve the Promise. async function main() { var users = await request .get('api.com/users'); console.log('users', users); } main();
  • 18. Error Handling #PROMISE GetUser() .catch(function (e) {
 console.error(e)
 })
 .then(function (success) {
 console.log(success)
 })
 #CALLBACK GetUser(function(err, user){ console.error(err)
 }); #ASYNC/AWAIT 
 try {
 var user = await GetUser(1)
 console.log(user);
 }
 catch(err) {
 console.log('Got an error:', err.message)
 }

  • 19. Callback vs Promise vs Async #PROMISE GetUser()
 .then(GetProfile)
 .then(GetAccount)
 .then(GetReport)
 .then(SendStatistics)
 .then(function (success) {
 console.log(success)
 })
 .catch(function (e) {
 console.error(e)
 }) #CALLBACK GetUser(function(err, user){ GetProfile(user, function(err, profile){ GetAccount(profile, function(err, acc){ GetReport(acc, function(err, report){ SendStatistics(report, function(e){ ... }); }); }); }); }); #ASYNC/AWAIT 
 async function SendAsync() {
 
 let user = await GetUser(1)
 let profile = await GetProfile(user);
 let account = await GetAccount(profile);
 let report = await GetReport(account);
 
 let send = SendStatistic(report);
 
 console.log(send)
 }