Last active
November 23, 2017 17:02
-
-
Save SonofNun15/f9accfcbbee7ae3407dda31c3a1d13d6 to your computer and use it in GitHub Desktop.
Asynchronous Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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