I am creating a learning module for my students where I am trying to demonstrate the power of promises vs callbacks. Unfortunately I am coming from a Python background so callback hell is not something I have had to deal with.
The task at hand is I want to convert an example that I used to demonstrate how async can produce unexpected results into one that produces the expected results using callbacks.
function print1() {
mimicAsync(1);
}
function print2() {
mimicAsync(2);
}
function print3() {
mimicAsync(3);
}
print1();
print2();
print3();
<script>
function mimicAsync(num) {
setTimeout(function() {
document.getElementById("output").innerHTML += num;
}, Math.floor(Math.random() * 1000));
}
</script>
<span id="output"></span>
I know how to do this with Promises, but I want to first show how unpleasant it is with callbacks. I came into JavaScript after Promises were introduced so have little experience with callback hell.