Skip to content

Instantly share code, notes, and snippets.

@billautomata
Created August 28, 2018 01:46
Show Gist options
  • Select an option

  • Save billautomata/58a8d4b8bc6b102f65841db80ad2c28f to your computer and use it in GitHub Desktop.

Select an option

Save billautomata/58a8d4b8bc6b102f65841db80ad2c28f to your computer and use it in GitHub Desktop.

Revisions

  1. billautomata created this gist Aug 28, 2018.
    47 changes: 47 additions & 0 deletions example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    // nest them

    var a = 0
    var b = 0

    fs.readFile('filename.txt', function(err,data){
    a = data
    fs.readFile('file2.txt', function(err,data){
    b = data
    console.log(a,b) // both values
    })
    })

    // use a library called async
    // npm install --save async

    var async = require('async')
    var fns = [] // array of functions
    var a = 0
    var b = 0

    // push a function on to the array
    fns.push(function(done){
    fs.readFile('filename.txt', function(err,data){
    a = data
    return done() // a special async function that signals to move on
    })
    })

    // push another function on to the array
    fns.push(function(done){
    fs.readFile('file2.txt', function(err,data){
    b = data
    return done() // a special async function that signals to move on
    })
    })

    // push the last function on to the array
    fns.push(function(done){
    console.log(a,b) // both values are populated
    return done()
    })

    async.series(fns) // this is where all the 3 functions you just pushed on to the array are run in order