Skip to content

Instantly share code, notes, and snippets.

@yeukhon
Last active August 29, 2015 14:04
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 yeukhon/a2254f1e5f8de63c8268 to your computer and use it in GitHub Desktop.
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/)
// 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