Skip to content

Instantly share code, notes, and snippets.

@billautomata
Created August 28, 2018 01:46
Show Gist options
  • Save billautomata/58a8d4b8bc6b102f65841db80ad2c28f to your computer and use it in GitHub Desktop.
Save billautomata/58a8d4b8bc6b102f65841db80ad2c28f to your computer and use it in GitHub Desktop.
dealing with callbacks
// 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment