JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/q.js/1.0.1/q.min.js"></script>
JavaScript
// 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.
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");