Last active
August 29, 2015 14:04
-
-
Save yeukhon/a2254f1e5f8de63c8268 to your computer and use it in GitHub Desktop.
Dummy example to show why we write asychronous code LOL (http://jsfiddle.net/T9feW/)
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
// See your dev console. Don't forget the reason you use promise | |
// is to write asynchronous code in synchronous way. | |
// We duplicate two instances of step1-3 whichever comes back first | |
// gets the counter = 1 and the latter one gets counter = 2. | |
// The message "end of program let's quit" will print before | |
// any result comes back. | |
// Require Q.js (just go to jsfiddle) | |
var counter = 0; | |
function step1() { | |
console.log("Executing step1 before returning a promise"); | |
return Q.delay(1000).then(function() { | |
console.log("Returning from step1"); | |
}); | |
} | |
function step2() { | |
console.log("Executing step2 before returning a promise"); | |
return Q.delay(2000).then(function() { | |
console.log("Returning from step2"); | |
}); | |
} | |
function step3() { | |
console.log("Executing step3 before returning a promise"); | |
return Q.delay(3000).then(function() { | |
console.log("Returning from step3"); | |
counter += 1; | |
console.log(counter); | |
}); | |
} | |
step1().then(step2).then(step3); | |
step1().then(step2).then(step3); | |
console.log("end of program let's quit"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment