SlideShare a Scribd company logo
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 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
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 

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

Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 

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); });