SlideShare a Scribd company logo
1 of 26
Download to read offline
Controlling the Callback Flow
Jason
NodeJs
Controlling the Callback Flow
● Understanding the boomerang effect
● Using async to control callback flow
Executing in Series
Executing in Parallel
Cascading
Queuing
Iterating
Mapping
Reducing
A demonstration of the boomerang effect.
var fs = require('fs');
function append_some_a_to_b(callback) {
fs.open(__dirname + '/a.txt', 'r', function(err, aFd) {
var buffer = new Buffer(10);
fs.read(aFd, buffer, 0, buffer.length, 0, function(err) {
fs.close(aFd, function(err) {
fs.open(__dirname + '/b.txt', 'a', function(err, bFd) {
fs.fstat(bFd, function(err, bStats) {
fs.write(bFd, buffer, 0, buffer.length, bStats.size,
function(err) {
fs.close(bFd, callback);
});
});
});
});
});
});
}
Using async to control callback flow
● To install async you include it in your package.json manifest or simply install
it
on your application root directory like this:
> npm install async
● The async module comes with a series of helper functions that allow you to
perform asynchronous iteration and flow control.
Executing in Series
series(tasks, [callback])
● Run the functions in the tasks array in series, each one running once the previous function has
completed.
● If any functions in the series pass an error to its callback, no more functions are run, and callback
is immediately called with the value of the error
● tasks - An array or object containing functions to run, each function is passed a callback(err,
result) it must call on completion with an error err (which can be null) and an optional result value
● callback - Callback receives an array of results when tasks have completed.
Executing in Series
var async = require('async');
async.series([
function(callback){
callback(null, 'one');
},
function(callback){
callback(null, 'two');
}
],
function(err, results){
if (err) { throw err; }
console.log('results: %j', results); // results is now equal to ['one', 'two']
});
Executing in Series
var async = require('async');
async.series({
one: function(callback){
setTimeout(function(){ callback(null, 1); }, 200);
},
two: function(callback){
setTimeout(function(){ callback(null, 2); }, 100);
}
},
function(err, results) {
if (err) { throw err; }
console.log('results: %j', results); // results is now equal to: {one: 1, two: 2}
});
Executing in Parallel
parallel(tasks, [callback])
● Run the tasks array of functions in parallel, without waiting until the previous function has
completed
● If any functions in the series pass an error to its callback, no more functions are run, and callback
is immediately called with the value of the error
● tasks - An array or object containing functions to run. Each function is passed a callback(err,
result) which it must call on completion with an error err (which can be null) and an optional result
value.
● callback(err, results) - An optional callback to run once all the functions have completed. This
function gets a results array (or object) containing all the result arguments passed to the task
Executing in Parallel
var async = require('async');
async.parallel([
function(callback){
setTimeout(function(){ callback(null, 'one'); }, 200);
},
function(callback){
setTimeout(function(){ callback(null, 'two'); }, 100);
}
],
function(err, results) {
if (err) { throw err; }
console.log('results: %j', results); // results is now equal to: {one: 1, two: 2}
});
Executing in Parallel
var async = require('async');
async.parallel({
one: function(callback){
setTimeout(function(){ callback(null, 1); }, 200);
},
two: function(callback){
setTimeout(function(){ callback(null, 2); }, 100);
}
},
function(err, results) {
if (err) { throw err; }
console.log('results: %j', results); // results is now equal to: {one: 1, two: 2}
});
Cascading
waterfall(tasks, [callback])
● Runs the tasks array of functions in series, each passing their results to the next in the array.
● If any of the tasks pass an error to their own callback, the next function is not executed, and the
main callback is immediately called with the error.
● tasks - An array of functions to run, each function is passed a callback(err, result1, result2, ...) it
must call on completion. The first argument is an error (which can be null) and any further
arguments will be passed as arguments in order to the next task.
● callback(err, [results]) - An optional callback to run once all the functions have completed. This will
be passed the results of the last task's callback.
Cascading
var async = require('async');
async.waterfall([
function(callback){
callback(null, 'one', 'two');
},
function(arg1, arg2, callback){
callback(null, 'three');
},
function(arg1, callback){
callback(null, 'done');
}
], function (err, result) {
console.log('result : ', result);
});
Queuing
queue(worker, concurrency)
● If you need to perform some repetitive asynchronous jobs and you want to control the
concurrency
● worker(task, callback) - An asynchronous function for processing a queued task, which must call
its callback(err) argument when finished, with an optional error as an argument.
● concurrency - An integer for determining how many worker functions should be run in parallel.
Queuing
var async = require('async');
var q = async.queue(function (task, callback) {
console.log('hello ' + task.name);
callback();
}, 2);
q.drain = function() { console.log('all items have been processed'); }
q.push( {name: 'foo'}, function (err) { console.log('finished processing foo'); });
q.push( {name: 'bar'}, function (err) { console.log('finished processing bar'); });
q.push( [{name: 'baz'},{name: 'bay'},{name: 'bax'}] , function (err) { console.log('finished processing item'); });
q.unshift( {name: 'bar'}, function (err) { console.log('finished processing bar'); });
Iterating
forEach(arr, iterator, callback)
● If you use this async.forEach function, you are invoking an iterator for each element in parallel
● iterator(item, callback) - A function to apply to each item in arr.
● callback(results) - A callback which is called when all iterator functions have finished, or an
error occurs.
Iterating
var async = require('async');
var results = {};
function iterator(value, callback) {
results[value] = Math.pow(value, 2);
callback();
}
async.forEach([1, 2, 3, 4], iterator, function(err){
if (err) { throw err; }
console.log('results: %j', results);
});
Output :
results: {“1”: 1, “2” : 4, “3” : 9, “4” : 16}
Mapping
map(arr, iterator, callback)
● Produces a new array of values by mapping each value in arr through the iterator function
● iterator(item, callback) - A function to apply to each item in arr. The iterator is passed a
callback(err, transformed) which must be called once it has completed with an error (which can be
null) and a transformed item.
● callback(err, results) - A callback which is called when all iterator functions have finished, or an
error occurs. Results is an array of the transformed items from the arr.
Mapping
var async = require('async');
function iterator(value, callback) {
callback(null, Math.pow(value, 2));
}
async.map([1, 2, 3, 4], iterator, function(err, results) {
if (err) {
throw err;
}
console.log('results: %j', results);
});
Output : results : [1,4,9,16]
Reducing
reduce(arr, memo, iterator, callback)
● Reduces array into a single value using an async iterator to return each successive step.
● memo - The initial state of the reduction.
● iterator(memo, item, callback) - A function applied to each item in the array to produce the next
step in the reduction. The iterator is passed a callback(err, reduction) which accepts an optional
error as its first argument, and the state of the reduction as the second.
● callback(err, result) - A callback which is called after all the iterator functions have finished. Result
is the reduced value.
Reducing
var async = require('async');
async.reduce([1,2,3], 0, function(memo, item, callback){
console.log(‘memo:‘ + memo, ‘item:’ + item);
callback(null, memo + item);
}, function(err, result){
console.log('Result : %j', result);
});
Output :
memo : 0 item : 1
memo : 1 item : 2
memo : 3 item : 3
Result : 6
Filtering
filter(arr, iterator, callback)
● Returns a new array of all the values in array which pass an async truth test.
● The callback for each iterator call only accepts a single argument of true or false
● It does not accept an error argument first!
Filtering
var async = require('async');
function filter(item, callback) {
callback(Math.pow(item, 2) > 10);
}
async.filter([1, 2, 3, 4, 5], filter, function(results)
{
console.log('Square value is greater than 10: %j', results);
});
Output : Square value is greater than 10: [4,5]
Filtering
var async = require('async');
var fs = require(‘fs’);
async.filter(['file1','file2','file3'], fs.exists, function(results){
// results now equals an array of the existing files
});
Detecting
detect(arr, iterator, callback)
● Returns the first value in array that passes an async truth test.
● The iterator is applied in parallel, meaning the first iterator to return true will fire the detect callback
with that result
Detecting
var async = require('async');
function filter(item, callback) {
callback(Math.pow(item, 2) > 10);
}
async.detect([1, 2, 3, 4, 5], filter, function(result)
{
console.log('Square value is greater than 10: %j', result);
});
Output : Square value is greater than 10: 4
Detecting
var async = require('async');
var fs = require(‘fs’);
async.detect(['file1','file2','file3'], fs.exists, function(results){
console.log("exist : ", result);
});

More Related Content

What's hot

Continuations
ContinuationsContinuations
Continuations
openbala
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 

What's hot (20)

Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
 
Slot shifting1
Slot shifting1Slot shifting1
Slot shifting1
 
Continuations
ContinuationsContinuations
Continuations
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
 
functions of C++
functions of C++functions of C++
functions of C++
 
functions
functionsfunctions
functions
 
Rxjs ppt
Rxjs pptRxjs ppt
Rxjs ppt
 
Pure Future
Pure FuturePure Future
Pure Future
 
Java script
Java scriptJava script
Java script
 
DSU C&C++ Practical File Diploma
DSU C&C++ Practical File DiplomaDSU C&C++ Practical File Diploma
DSU C&C++ Practical File Diploma
 
M11 operator overloading and type conversion
M11 operator overloading and type conversionM11 operator overloading and type conversion
M11 operator overloading and type conversion
 
Lambda Expressions in C++
Lambda Expressions in C++Lambda Expressions in C++
Lambda Expressions in C++
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88The Ring programming language version 1.3 book - Part 59 of 88
The Ring programming language version 1.3 book - Part 59 of 88
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diploma
 
MATLAB Scripts - Examples
MATLAB Scripts - ExamplesMATLAB Scripts - Examples
MATLAB Scripts - Examples
 
Berlin meetup
Berlin meetupBerlin meetup
Berlin meetup
 
Operator Overloading & Type Conversions
Operator Overloading & Type ConversionsOperator Overloading & Type Conversions
Operator Overloading & Type Conversions
 
Understanding Javascript Engine to Code Better
Understanding Javascript Engine to Code BetterUnderstanding Javascript Engine to Code Better
Understanding Javascript Engine to Code Better
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 

Similar to Node js

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 

Similar to Node js (20)

Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
Async History - javascript
Async History - javascriptAsync History - javascript
Async History - javascript
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Javascript
JavascriptJavascript
Javascript
 
Tail recursion
Tail recursionTail recursion
Tail recursion
 
Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structure
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
8558537werr.pptx
8558537werr.pptx8558537werr.pptx
8558537werr.pptx
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstitute
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 

More from LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection & activator
Reflection & activatorReflection & activator
Reflection & activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Recently uploaded

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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
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
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 

Node js

  • 1. Controlling the Callback Flow Jason NodeJs
  • 2. Controlling the Callback Flow ● Understanding the boomerang effect ● Using async to control callback flow Executing in Series Executing in Parallel Cascading Queuing Iterating Mapping Reducing
  • 3. A demonstration of the boomerang effect. var fs = require('fs'); function append_some_a_to_b(callback) { fs.open(__dirname + '/a.txt', 'r', function(err, aFd) { var buffer = new Buffer(10); fs.read(aFd, buffer, 0, buffer.length, 0, function(err) { fs.close(aFd, function(err) { fs.open(__dirname + '/b.txt', 'a', function(err, bFd) { fs.fstat(bFd, function(err, bStats) { fs.write(bFd, buffer, 0, buffer.length, bStats.size, function(err) { fs.close(bFd, callback); }); }); }); }); }); }); }
  • 4. Using async to control callback flow ● To install async you include it in your package.json manifest or simply install it on your application root directory like this: > npm install async ● The async module comes with a series of helper functions that allow you to perform asynchronous iteration and flow control.
  • 5. Executing in Series series(tasks, [callback]) ● Run the functions in the tasks array in series, each one running once the previous function has completed. ● If any functions in the series pass an error to its callback, no more functions are run, and callback is immediately called with the value of the error ● tasks - An array or object containing functions to run, each function is passed a callback(err, result) it must call on completion with an error err (which can be null) and an optional result value ● callback - Callback receives an array of results when tasks have completed.
  • 6. Executing in Series var async = require('async'); async.series([ function(callback){ callback(null, 'one'); }, function(callback){ callback(null, 'two'); } ], function(err, results){ if (err) { throw err; } console.log('results: %j', results); // results is now equal to ['one', 'two'] });
  • 7. Executing in Series var async = require('async'); async.series({ one: function(callback){ setTimeout(function(){ callback(null, 1); }, 200); }, two: function(callback){ setTimeout(function(){ callback(null, 2); }, 100); } }, function(err, results) { if (err) { throw err; } console.log('results: %j', results); // results is now equal to: {one: 1, two: 2} });
  • 8. Executing in Parallel parallel(tasks, [callback]) ● Run the tasks array of functions in parallel, without waiting until the previous function has completed ● If any functions in the series pass an error to its callback, no more functions are run, and callback is immediately called with the value of the error ● tasks - An array or object containing functions to run. Each function is passed a callback(err, result) which it must call on completion with an error err (which can be null) and an optional result value. ● callback(err, results) - An optional callback to run once all the functions have completed. This function gets a results array (or object) containing all the result arguments passed to the task
  • 9. Executing in Parallel var async = require('async'); async.parallel([ function(callback){ setTimeout(function(){ callback(null, 'one'); }, 200); }, function(callback){ setTimeout(function(){ callback(null, 'two'); }, 100); } ], function(err, results) { if (err) { throw err; } console.log('results: %j', results); // results is now equal to: {one: 1, two: 2} });
  • 10. Executing in Parallel var async = require('async'); async.parallel({ one: function(callback){ setTimeout(function(){ callback(null, 1); }, 200); }, two: function(callback){ setTimeout(function(){ callback(null, 2); }, 100); } }, function(err, results) { if (err) { throw err; } console.log('results: %j', results); // results is now equal to: {one: 1, two: 2} });
  • 11. Cascading waterfall(tasks, [callback]) ● Runs the tasks array of functions in series, each passing their results to the next in the array. ● If any of the tasks pass an error to their own callback, the next function is not executed, and the main callback is immediately called with the error. ● tasks - An array of functions to run, each function is passed a callback(err, result1, result2, ...) it must call on completion. The first argument is an error (which can be null) and any further arguments will be passed as arguments in order to the next task. ● callback(err, [results]) - An optional callback to run once all the functions have completed. This will be passed the results of the last task's callback.
  • 12. Cascading var async = require('async'); async.waterfall([ function(callback){ callback(null, 'one', 'two'); }, function(arg1, arg2, callback){ callback(null, 'three'); }, function(arg1, callback){ callback(null, 'done'); } ], function (err, result) { console.log('result : ', result); });
  • 13. Queuing queue(worker, concurrency) ● If you need to perform some repetitive asynchronous jobs and you want to control the concurrency ● worker(task, callback) - An asynchronous function for processing a queued task, which must call its callback(err) argument when finished, with an optional error as an argument. ● concurrency - An integer for determining how many worker functions should be run in parallel.
  • 14. Queuing var async = require('async'); var q = async.queue(function (task, callback) { console.log('hello ' + task.name); callback(); }, 2); q.drain = function() { console.log('all items have been processed'); } q.push( {name: 'foo'}, function (err) { console.log('finished processing foo'); }); q.push( {name: 'bar'}, function (err) { console.log('finished processing bar'); }); q.push( [{name: 'baz'},{name: 'bay'},{name: 'bax'}] , function (err) { console.log('finished processing item'); }); q.unshift( {name: 'bar'}, function (err) { console.log('finished processing bar'); });
  • 15. Iterating forEach(arr, iterator, callback) ● If you use this async.forEach function, you are invoking an iterator for each element in parallel ● iterator(item, callback) - A function to apply to each item in arr. ● callback(results) - A callback which is called when all iterator functions have finished, or an error occurs.
  • 16. Iterating var async = require('async'); var results = {}; function iterator(value, callback) { results[value] = Math.pow(value, 2); callback(); } async.forEach([1, 2, 3, 4], iterator, function(err){ if (err) { throw err; } console.log('results: %j', results); }); Output : results: {“1”: 1, “2” : 4, “3” : 9, “4” : 16}
  • 17. Mapping map(arr, iterator, callback) ● Produces a new array of values by mapping each value in arr through the iterator function ● iterator(item, callback) - A function to apply to each item in arr. The iterator is passed a callback(err, transformed) which must be called once it has completed with an error (which can be null) and a transformed item. ● callback(err, results) - A callback which is called when all iterator functions have finished, or an error occurs. Results is an array of the transformed items from the arr.
  • 18. Mapping var async = require('async'); function iterator(value, callback) { callback(null, Math.pow(value, 2)); } async.map([1, 2, 3, 4], iterator, function(err, results) { if (err) { throw err; } console.log('results: %j', results); }); Output : results : [1,4,9,16]
  • 19. Reducing reduce(arr, memo, iterator, callback) ● Reduces array into a single value using an async iterator to return each successive step. ● memo - The initial state of the reduction. ● iterator(memo, item, callback) - A function applied to each item in the array to produce the next step in the reduction. The iterator is passed a callback(err, reduction) which accepts an optional error as its first argument, and the state of the reduction as the second. ● callback(err, result) - A callback which is called after all the iterator functions have finished. Result is the reduced value.
  • 20. Reducing var async = require('async'); async.reduce([1,2,3], 0, function(memo, item, callback){ console.log(‘memo:‘ + memo, ‘item:’ + item); callback(null, memo + item); }, function(err, result){ console.log('Result : %j', result); }); Output : memo : 0 item : 1 memo : 1 item : 2 memo : 3 item : 3 Result : 6
  • 21. Filtering filter(arr, iterator, callback) ● Returns a new array of all the values in array which pass an async truth test. ● The callback for each iterator call only accepts a single argument of true or false ● It does not accept an error argument first!
  • 22. Filtering var async = require('async'); function filter(item, callback) { callback(Math.pow(item, 2) > 10); } async.filter([1, 2, 3, 4, 5], filter, function(results) { console.log('Square value is greater than 10: %j', results); }); Output : Square value is greater than 10: [4,5]
  • 23. Filtering var async = require('async'); var fs = require(‘fs’); async.filter(['file1','file2','file3'], fs.exists, function(results){ // results now equals an array of the existing files });
  • 24. Detecting detect(arr, iterator, callback) ● Returns the first value in array that passes an async truth test. ● The iterator is applied in parallel, meaning the first iterator to return true will fire the detect callback with that result
  • 25. Detecting var async = require('async'); function filter(item, callback) { callback(Math.pow(item, 2) > 10); } async.detect([1, 2, 3, 4, 5], filter, function(result) { console.log('Square value is greater than 10: %j', result); }); Output : Square value is greater than 10: 4
  • 26. Detecting var async = require('async'); var fs = require(‘fs’); async.detect(['file1','file2','file3'], fs.exists, function(results){ console.log("exist : ", result); });