Last active
August 29, 2015 14:12
-
-
Save limianwang/90da0a4276c64bc9e17b to your computer and use it in GitHub Desktop.
Creating truly asynchronous functions
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
/* | |
When coding in Node.js, you will often/most likely be dealing with some I/O, which involves asynchronous processes. Therefore, building a standard for coding is paramount. | |
Consider the following code: | |
*/ | |
var fs = require('fs'); | |
function logA(command, data, done) { | |
if(command === 'write') { | |
fs.writeFile('somefile', data, function(err) { | |
console.log(data); | |
done(); | |
}); | |
} else { | |
console.log(data); | |
done(); | |
} | |
} | |
/** | |
* now consider the following use case: | |
*/ | |
logA('read', 'hello', function(err) { | |
console.log('world'); | |
}); | |
console.log('welcome'); | |
/** | |
* The output will be: | |
* > hello | |
* > world | |
* > welcome | |
*/ | |
// Now consider the following use case? | |
logB('write', 'hello', function(err) { | |
console.log('world'); | |
}); | |
console.log('Welcome'); | |
/** | |
* The output would be: | |
* > welcome | |
* > hello | |
* > world | |
*/ | |
/** | |
* What happened? Crap, this `logA` function is _sometimes_ synchronous and _sometimes_ asynchronous! | |
* It gets people confused. To solve this, you always make it async. | |
*/ | |
function modifiedLogA(cmd, data, done) { | |
if(cmd === 'write') { | |
fs.writeFile('somefile', data, function(err) { | |
console.log(data); | |
done(); | |
}); | |
} else { | |
// This gets put into the event-loop, for the _next_ iteration | |
// now this function is truly async regardless of conditions. | |
setImmediate(function() { | |
console.log(data); | |
done(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment