So far in this chapter, we've seen how to use promises to run single asynchronous tasks. This is helpful but doesn't provide a significant improvement over the callback pattern. The real advantage that promises offer comes when they are composed.
In this recipe, we'll use promises to combine asynchronous functions in series.
This recipe assumes that you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
- Open your command-line application and navigate to your workspace.
- Create a new folder named
3-04-chaining-promises.
- Copy or create an
index.html
that loads and runs amain
function frommain.js
.
- Create a
main.js
file that creates a promise. Resolve a random number from the promise:
new Promise(function (resolve) { resolve(Math.random()); }); );
- Chain a
then
call off of the promise. Returntrue
from the callback if the random value is greater than or...