Skip to content

Instantly share code, notes, and snippets.

@SonofNun15
Last active November 23, 2017 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SonofNun15/f9accfcbbee7ae3407dda31c3a1d13d6 to your computer and use it in GitHub Desktop.
Save SonofNun15/f9accfcbbee7ae3407dda31c3a1d13d6 to your computer and use it in GitHub Desktop.
Asynchronous Javascript
const start = require('./start')
const run = require('./run')
// INCORRECT approach:
// start doesn't return anything immediately, so this variable
// will be undefined.
const willBeUndefined = start((myPet) => {
// We can log the pet which start creates
console.log('myPet = ' + JSON.stringify(myPet))
})
// If we call run outside of the start callback it will run
// before start finishes. We can't guarantee that start
// has completed unless we are inside of the start callback.
run(willBeUndefined)
// CORRECT approach:
// start receives a callback which is called once start is completed.
// We call run() in this callback to run after start
start((myPet) => {
run(myPet)
})
const rl = require('readline')
function start(callback) {
// use readline to get pet name + etc
rl.question('name?', (name) => {
pet = { name }
// callback is called after question completes because
// it is included inside of the question callback
callback(pet)
})
// if we called callback here it would happen immediately
// (before question completes) and we would not have
// access to the response to the question
}
module.exports = start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment