SlideShare une entreprise Scribd logo
1  sur  30
Télécharger pour lire hors ligne
Flow Control in Node.js
         송형주
Profile
● 삼성전자 소프트웨어센터
  Web Convergence Lab.

● 블로그
  Inside.JS (http://www.nodejs-kr.
  org/insidejs)
var fs = require('fs')
                               Synchronous Programming
  , path = './sync.txt';

var stats = fs.statSync(path);

if (stats == undefined) {
  // read the contents of this file
  var content = fs.readFileSync(__filename);
}

var code = content.toString();
// write the content to sync.txt
var err = fs.writeFileSync(path, code);
if(err) throw err;
console.log('sync.txt created!');

console.log(‘Another Task’);
var fs = require('fs')
                                   Asynchronous Programming
  , path = './async.txt';

// check if async.txt exists
fs.stat(path, function(err, stats) {
  if (stats == undefined) {
    // read the contents of this file
    fs.readFile(__filename, function(err, content) {
      var code = content.toString();
      // write the content to async.txt
      fs.writeFile(path, code, function(err) {
        if (err) throw err;
        console.log('async.txt created!');
      });
    });
  }
});

console.log(‘Another Task’);
Node.js programming is not easy.
var open = false;

setTimeout(function () {
  open = true;
}, 1000);

while(!open) {
  // wait
}

console.log('opened!');
Nested Callback Problem
async1(function(input, result1) {
 async2(function(result2) {
   async3(function(result3) {
    async4(function(result4) {
     async5(function(output) {
        // do something with output
     });
    });
   });
 });
})
Flow Control Problem

   for(var i = 1; i <= 1000; i++) {
     fs.readFile('./'+i+'.txt',
          function() {
         // do something with the file
         }
     );
   }

   do_next_part();
Why Flow Control?
• Asynchronous Programming

• Issues
 – Doing a bunch of things in a specific order
 – Knowing when task is done.
 – Nested Callback
 – Collecting result data
Flow Control Pattern

 • Serial Execution
 • Parallel Execution
 • Limited Parallel Execution
Serial Execution
                   Start


                 Task1


                 Task2


                 Task3

            Continue when tasks
                  complete
Parallel Execution
                   Start




   Task1          Task2            Task3




             Continue When tasks
                   complete
Flow Control Libraries
• Async – providing various control function
• Step – simple and easy to use
• Slide – used in the npm client code
• Seq
• Nue
•…
Node.js Coding Conventions
• Two kinds of functions :
 – Action Function : Take action
 – Callback Function : Get results


• Action functions
 – last argument is always a callback function


• Callback functions
 – first argument is always an error or null.
Action                           Callback
       Function               Result     Function

(Action Function Developer)            (Action Function User)
Action Function Example
 function actor (some, args, cb) {
   // last argument is callback
   // optional args:
   if (!cb && typeof(args) === "function")
      cb = args, args = [];

     // do something, and then:

     if (failed) cb(new Error("failed!"))
     else cb(null, optionalData)
 }
Action                 Callback
 Function     Result     Function



Action Function과 Callback
Function 사이는 결과를 어떻게 넘길 지에 대
한 인터페이스가 명확히 규정되어 한다.
Action Function Example
// return true if a path is either
// a symlink or a directory.

function isLinkOrDir (path, cb) {
  fs.lstat(path, function (er, s) {
    if (er) return cb(er);
    return cb(null,
        s.isDirectory() ||
        s.isSymbolicLink());
  });
}           isLinkorDir
                                    Result       cb
           fs.lstat           _cb
                      er, s         er, result
Usecases : Parallel Execution
● I have a list of 10 files, and need to read all of
 them, and then continue when they're all done.
  
● I have a dozen URLs, and need to fetch them all,
 and then continue when they're all done.

●I have 4 connected users, and need to send a
 message to all of them, and then continue when
 that's done.
function asyncMap (list, fn, cb_) {
  var n = list.length
  , results = []
  , errState = null;

    function cb (er, data) {
      if (errState) return;
      if (er) return cb(errState = er);
      results.push(data);
      if (--n === 0) // 모든 리스트 처리 완료시
        return cb_(null, results);
    }

    // action code
    list.forEach(function (l) {
      fn(l, cb);
    });
}
asyncMap
    list
                  result

                      중간 결과 저                 cb_
                      장


     fn             cb
           err,                 err, result
           data
Usecases : AsyncMap
        function writeFiles (files, what, cb) {
          asyncMap(files,
              function (f, cb_) {
                fs.writeFile(f,what,cb_);
              },                       cb_는 asyncMap의 내부 함수임
              cb
          );
        }

        writeFiles([my,file,list], "foo", cb);


        writeFiles
        asyncMap
files                                       cb
        list

         fn    cb_
                            err
This implementation is fine if order doesn't
matter, but what if it does?
function asyncMap(list, fn, cb_) {
  var n = list.length
    , results = []
    , errState = null;

    function cbGen (i) {
      return function cb(er, data) {
        if (errState) return;
        if (er)
          return cb(errState = er);
        results[i] = data;
        if (-- n === 0)
          return cb_(null, results);
      }
    }
    list.forEach(function (l, i) {
      fn(l, cbGen(i));
    });
}
usecase: Serial Execution


 • I have to do a bunch of things, in order.
 Get db credentials out of a file, read the data
 from the db, write that data to another file.
  
 • If anything fails, do not continue.
function chain (things, cb) {
  (function LOOP (i, len) {
    if (i >= len)
       return cb();
    things[i](function (er) {
       if (er)
         return cb(er);
       LOOP(i + 1, len)
    })
  })(0, things.length)
}
chain
things
                         LOOP,0



         things[0]       LOOP,1


         things[1]       LOOP,2



         things[2]       LOOP, 3   cb
var fs = require('fs');
var async = require('async');
                                             Async Module Example
var path = './async.txt';
async.waterfall([
    // check if async.txt exists
    function(cb) {
        fs.stat(path, function(err, stats) {
            if (stats == undefined) cb(null);
            else console.log('async.txt exists');
        });
    },
    // read the contents of this file
    function(cb) {
        fs.readFile(__filename, function(err, content) {
            var code = content.toString();
            cb(null, code);
        });
    },
    // write the content to async.txt
    function(code, cb) {
        fs.writeFile(path, code, function(err) {
            if (err) throw err;
            console.log('async.txt created!');
        });
    }
Step Module Example

Step(
   function readSelf() {
      fs.readFile(__filename, 'utf8', this);
   },
   function capitalize(err, text) {
      if (err) throw err;
      return text.toUpperCase();
   },
   function showIt(err, newText) {
      if (err) throw err;
      console.log(newText);
   }
);
Step Module Example
Step(
  // Loads two files in parallel
  function loadStuff() {
     fs.readFile(__filename, this.parallel());
     fs.readFile("/etc/passwd", this.
parallel());
  },
  // Show the result when done
  function showStuff(err, code, users) {
     if (err) throw err;
     console.log(code);
     console.log(users);
  }
)
Reference
● slide module guide (Issacs) https://github.
  com/isaacs/slide-flow-control/blob/master/nodejs-
  controlling-flow.pdf

Contenu connexe

Tendances

Qtp Training Deepti 4 Of 4493
Qtp Training Deepti 4 Of 4493Qtp Training Deepti 4 Of 4493
Qtp Training Deepti 4 Of 4493
Azhar Satti
 
Lightweight wrapper for Hive on Amazon EMR
Lightweight wrapper for Hive on Amazon EMRLightweight wrapper for Hive on Amazon EMR
Lightweight wrapper for Hive on Amazon EMR
Shinji Tanaka
 

Tendances (20)

ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)Kotlin For Android - Basics (part 1 of 7)
Kotlin For Android - Basics (part 1 of 7)
 
[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화[232] TensorRT를 활용한 딥러닝 Inference 최적화
[232] TensorRT를 활용한 딥러닝 Inference 최적화
 
[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화[232]TensorRT를 활용한 딥러닝 Inference 최적화
[232]TensorRT를 활용한 딥러닝 Inference 최적화
 
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)Kotlin For Android - Constructors and Control Flow (part 2 of 7)
Kotlin For Android - Constructors and Control Flow (part 2 of 7)
 
Gogo shell
Gogo shellGogo shell
Gogo shell
 
Xanadu - Java Chapter Meeting
Xanadu - Java Chapter Meeting Xanadu - Java Chapter Meeting
Xanadu - Java Chapter Meeting
 
Talk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe ConversetTalk KVO with rac by Philippe Converset
Talk KVO with rac by Philippe Converset
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with files
 
Automating with ansible (Part c)
Automating with ansible (Part c) Automating with ansible (Part c)
Automating with ansible (Part c)
 
CQL: SQL In Cassandra
CQL: SQL In CassandraCQL: SQL In Cassandra
CQL: SQL In Cassandra
 
PostgreSQL and PL/Java
PostgreSQL and PL/JavaPostgreSQL and PL/Java
PostgreSQL and PL/Java
 
Using zone.js
Using zone.jsUsing zone.js
Using zone.js
 
Scheming Defaults
Scheming DefaultsScheming Defaults
Scheming Defaults
 
ReactPHP – reaktor jądrowy w PHP
ReactPHP – reaktor jądrowy w PHPReactPHP – reaktor jądrowy w PHP
ReactPHP – reaktor jądrowy w PHP
 
Qtp Training Deepti 4 Of 4493
Qtp Training Deepti 4 Of 4493Qtp Training Deepti 4 Of 4493
Qtp Training Deepti 4 Of 4493
 
C++ prgms io file unit 7
C++ prgms io file unit 7C++ prgms io file unit 7
C++ prgms io file unit 7
 
LINE iOS開発で実践しているGit tips
LINE iOS開発で実践しているGit tipsLINE iOS開発で実践しているGit tips
LINE iOS開発で実践しているGit tips
 
Lightweight wrapper for Hive on Amazon EMR
Lightweight wrapper for Hive on Amazon EMRLightweight wrapper for Hive on Amazon EMR
Lightweight wrapper for Hive on Amazon EMR
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 

En vedette

Corporate Wellness - Presented by Beneplan & the House of Verona
Corporate Wellness - Presented by Beneplan & the House of VeronaCorporate Wellness - Presented by Beneplan & the House of Verona
Corporate Wellness - Presented by Beneplan & the House of Verona
Yafa Sakkejha
 
E twinning contact_seminar
E twinning contact_seminarE twinning contact_seminar
E twinning contact_seminar
ivanabrabcova
 
PowerVote Presentation
PowerVote PresentationPowerVote Presentation
PowerVote Presentation
Didier Moulin
 
myStratex Strategy Board Game
myStratex Strategy Board GamemyStratex Strategy Board Game
myStratex Strategy Board Game
FabStart
 
Powerpoint Sample
Powerpoint SamplePowerpoint Sample
Powerpoint Sample
CPW
 
How stupid can we get
How stupid can we getHow stupid can we get
How stupid can we get
guest0437b8
 

En vedette (20)

안드로이드 멀티스레딩 입문 송형주
안드로이드 멀티스레딩 입문 송형주안드로이드 멀티스레딩 입문 송형주
안드로이드 멀티스레딩 입문 송형주
 
Gamification in Social Media
Gamification in Social MediaGamification in Social Media
Gamification in Social Media
 
Treadmill Talk Show - Exercise Boosting Creativity
Treadmill Talk Show - Exercise Boosting CreativityTreadmill Talk Show - Exercise Boosting Creativity
Treadmill Talk Show - Exercise Boosting Creativity
 
Corporate Wellness - Presented by Beneplan & the House of Verona
Corporate Wellness - Presented by Beneplan & the House of VeronaCorporate Wellness - Presented by Beneplan & the House of Verona
Corporate Wellness - Presented by Beneplan & the House of Verona
 
Marketing Innovation In India
Marketing Innovation In IndiaMarketing Innovation In India
Marketing Innovation In India
 
E twinning contact_seminar
E twinning contact_seminarE twinning contact_seminar
E twinning contact_seminar
 
PowerVote Presentation
PowerVote PresentationPowerVote Presentation
PowerVote Presentation
 
The 10 Trends Shaping the Future of South African Brands in 2012
The 10 Trends Shaping the Future of South African Brands in 2012The 10 Trends Shaping the Future of South African Brands in 2012
The 10 Trends Shaping the Future of South African Brands in 2012
 
VMWare Wpg Jeff Franz-Lien
VMWare Wpg   Jeff Franz-LienVMWare Wpg   Jeff Franz-Lien
VMWare Wpg Jeff Franz-Lien
 
Sled Dog Race
Sled Dog RaceSled Dog Race
Sled Dog Race
 
Mobile Congress Presentation
Mobile Congress PresentationMobile Congress Presentation
Mobile Congress Presentation
 
Wta may2012 fnpw
Wta may2012 fnpwWta may2012 fnpw
Wta may2012 fnpw
 
myStratex Strategy Board Game
myStratex Strategy Board GamemyStratex Strategy Board Game
myStratex Strategy Board Game
 
Jaroslav Seifert - Look at book
Jaroslav Seifert - Look at bookJaroslav Seifert - Look at book
Jaroslav Seifert - Look at book
 
NSW Land for Wildlife
NSW Land for WildlifeNSW Land for Wildlife
NSW Land for Wildlife
 
Powerpoint Sample
Powerpoint SamplePowerpoint Sample
Powerpoint Sample
 
Abu Dhabi Island: Analysis of Development and Vegetation Change Using Remote ...
Abu Dhabi Island: Analysis of Development and Vegetation Change Using Remote ...Abu Dhabi Island: Analysis of Development and Vegetation Change Using Remote ...
Abu Dhabi Island: Analysis of Development and Vegetation Change Using Remote ...
 
How stupid can we get
How stupid can we getHow stupid can we get
How stupid can we get
 
Fazail-e-misvak
Fazail-e-misvakFazail-e-misvak
Fazail-e-misvak
 
Smart Networking
Smart NetworkingSmart Networking
Smart Networking
 

Similaire à Flow control in node.js

Node js
Node jsNode js
Node js
hazzaz
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
To Infinity & Beyond: Protocols & sequences in Node - Part 1
To Infinity & Beyond: Protocols & sequences in Node - Part 1To Infinity & Beyond: Protocols & sequences in Node - Part 1
To Infinity & Beyond: Protocols & sequences in Node - Part 1
Bahul Neel Upadhyaya
 
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
 

Similaire à Flow control in node.js (20)

Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Node js
Node jsNode js
Node js
 
Asynchronous programming with java script and node.js
Asynchronous programming with java script and node.jsAsynchronous programming with java script and node.js
Asynchronous programming with java script and node.js
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
 
To Infinity & Beyond: Protocols & sequences in Node - Part 1
To Infinity & Beyond: Protocols & sequences in Node - Part 1To Infinity & Beyond: Protocols & sequences in Node - Part 1
To Infinity & Beyond: Protocols & sequences in Node - Part 1
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
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
 
NodeJs
NodeJsNodeJs
NodeJs
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 

Plus de iamhjoo (송형주) (8)

AR/VR 기술 트렌드와 Immersive Web 동향
AR/VR 기술 트렌드와 Immersive Web 동향AR/VR 기술 트렌드와 Immersive Web 동향
AR/VR 기술 트렌드와 Immersive Web 동향
 
Second.s 분석 by_송형주
Second.s 분석 by_송형주Second.s 분석 by_송형주
Second.s 분석 by_송형주
 
Kernel 2.6 makefile_분석(송형주)
Kernel 2.6 makefile_분석(송형주)Kernel 2.6 makefile_분석(송형주)
Kernel 2.6 makefile_분석(송형주)
 
Flow Control in Node.js
Flow Control in Node.jsFlow Control in Node.js
Flow Control in Node.js
 
Power Manager Service 송형주 Rev02
Power Manager Service 송형주 Rev02Power Manager Service 송형주 Rev02
Power Manager Service 송형주 Rev02
 
안드로이드 스터디 Jni 발표 자료 Rev05 송형주
안드로이드 스터디 Jni 발표 자료 Rev05 송형주안드로이드 스터디 Jni 발표 자료 Rev05 송형주
안드로이드 스터디 Jni 발표 자료 Rev05 송형주
 
Bootchart 송형주
Bootchart 송형주Bootchart 송형주
Bootchart 송형주
 
About Init In Android By Andstudy
About Init In Android By AndstudyAbout Init In Android By Andstudy
About Init In Android By Andstudy
 

Dernier

Dernier (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
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?
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Flow control in node.js

  • 1. Flow Control in Node.js 송형주
  • 2. Profile ● 삼성전자 소프트웨어센터 Web Convergence Lab. ● 블로그 Inside.JS (http://www.nodejs-kr. org/insidejs)
  • 3. var fs = require('fs') Synchronous Programming , path = './sync.txt'; var stats = fs.statSync(path); if (stats == undefined) { // read the contents of this file var content = fs.readFileSync(__filename); } var code = content.toString(); // write the content to sync.txt var err = fs.writeFileSync(path, code); if(err) throw err; console.log('sync.txt created!'); console.log(‘Another Task’);
  • 4. var fs = require('fs') Asynchronous Programming , path = './async.txt'; // check if async.txt exists fs.stat(path, function(err, stats) { if (stats == undefined) { // read the contents of this file fs.readFile(__filename, function(err, content) { var code = content.toString(); // write the content to async.txt fs.writeFile(path, code, function(err) { if (err) throw err; console.log('async.txt created!'); }); }); } }); console.log(‘Another Task’);
  • 5. Node.js programming is not easy. var open = false; setTimeout(function () { open = true; }, 1000); while(!open) { // wait } console.log('opened!');
  • 6. Nested Callback Problem async1(function(input, result1) { async2(function(result2) { async3(function(result3) { async4(function(result4) { async5(function(output) { // do something with output }); }); }); }); })
  • 7. Flow Control Problem for(var i = 1; i <= 1000; i++) { fs.readFile('./'+i+'.txt', function() { // do something with the file } ); } do_next_part();
  • 8. Why Flow Control? • Asynchronous Programming • Issues – Doing a bunch of things in a specific order – Knowing when task is done. – Nested Callback – Collecting result data
  • 9. Flow Control Pattern • Serial Execution • Parallel Execution • Limited Parallel Execution
  • 10. Serial Execution Start Task1 Task2 Task3 Continue when tasks complete
  • 11. Parallel Execution Start Task1 Task2 Task3 Continue When tasks complete
  • 12. Flow Control Libraries • Async – providing various control function • Step – simple and easy to use • Slide – used in the npm client code • Seq • Nue •…
  • 13. Node.js Coding Conventions • Two kinds of functions : – Action Function : Take action – Callback Function : Get results • Action functions – last argument is always a callback function • Callback functions – first argument is always an error or null.
  • 14. Action Callback Function Result Function (Action Function Developer) (Action Function User)
  • 15. Action Function Example function actor (some, args, cb) { // last argument is callback // optional args: if (!cb && typeof(args) === "function") cb = args, args = []; // do something, and then: if (failed) cb(new Error("failed!")) else cb(null, optionalData) }
  • 16. Action Callback Function Result Function Action Function과 Callback Function 사이는 결과를 어떻게 넘길 지에 대 한 인터페이스가 명확히 규정되어 한다.
  • 17. Action Function Example // return true if a path is either // a symlink or a directory. function isLinkOrDir (path, cb) { fs.lstat(path, function (er, s) { if (er) return cb(er); return cb(null, s.isDirectory() || s.isSymbolicLink()); }); } isLinkorDir Result cb fs.lstat _cb er, s er, result
  • 18. Usecases : Parallel Execution ● I have a list of 10 files, and need to read all of them, and then continue when they're all done.   ● I have a dozen URLs, and need to fetch them all, and then continue when they're all done. ●I have 4 connected users, and need to send a message to all of them, and then continue when that's done.
  • 19. function asyncMap (list, fn, cb_) { var n = list.length , results = [] , errState = null; function cb (er, data) { if (errState) return; if (er) return cb(errState = er); results.push(data); if (--n === 0) // 모든 리스트 처리 완료시 return cb_(null, results); } // action code list.forEach(function (l) { fn(l, cb); }); }
  • 20. asyncMap list result 중간 결과 저 cb_ 장 fn cb err, err, result data
  • 21. Usecases : AsyncMap function writeFiles (files, what, cb) { asyncMap(files, function (f, cb_) { fs.writeFile(f,what,cb_); }, cb_는 asyncMap의 내부 함수임 cb ); } writeFiles([my,file,list], "foo", cb); writeFiles asyncMap files cb list fn cb_ err
  • 22. This implementation is fine if order doesn't matter, but what if it does?
  • 23. function asyncMap(list, fn, cb_) { var n = list.length , results = [] , errState = null; function cbGen (i) { return function cb(er, data) { if (errState) return; if (er) return cb(errState = er); results[i] = data; if (-- n === 0) return cb_(null, results); } } list.forEach(function (l, i) { fn(l, cbGen(i)); }); }
  • 24. usecase: Serial Execution • I have to do a bunch of things, in order. Get db credentials out of a file, read the data from the db, write that data to another file.   • If anything fails, do not continue.
  • 25. function chain (things, cb) { (function LOOP (i, len) { if (i >= len) return cb(); things[i](function (er) { if (er) return cb(er); LOOP(i + 1, len) }) })(0, things.length) }
  • 26. chain things LOOP,0 things[0] LOOP,1 things[1] LOOP,2 things[2] LOOP, 3 cb
  • 27. var fs = require('fs'); var async = require('async'); Async Module Example var path = './async.txt'; async.waterfall([ // check if async.txt exists function(cb) { fs.stat(path, function(err, stats) { if (stats == undefined) cb(null); else console.log('async.txt exists'); }); }, // read the contents of this file function(cb) { fs.readFile(__filename, function(err, content) { var code = content.toString(); cb(null, code); }); }, // write the content to async.txt function(code, cb) { fs.writeFile(path, code, function(err) { if (err) throw err; console.log('async.txt created!'); }); }
  • 28. Step Module Example Step( function readSelf() { fs.readFile(__filename, 'utf8', this); }, function capitalize(err, text) { if (err) throw err; return text.toUpperCase(); }, function showIt(err, newText) { if (err) throw err; console.log(newText); } );
  • 29. Step Module Example Step( // Loads two files in parallel function loadStuff() { fs.readFile(__filename, this.parallel()); fs.readFile("/etc/passwd", this. parallel()); }, // Show the result when done function showStuff(err, code, users) { if (err) throw err; console.log(code); console.log(users); } )
  • 30. Reference ● slide module guide (Issacs) https://github. com/isaacs/slide-flow-control/blob/master/nodejs- controlling-flow.pdf