Awaiting multiple results in a series
Sometimes it's necessary to arrange asynchronous operations in a series. In previous recipes, we've seen how to do this with Promise.then. In this recipe, we'll see how to do the same thing with the await operator.
Getting ready
This recipe assumes 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.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
04-03-async-function-Promise-chain. - Copy or create an
index.htmlthat loads and runs amainfunction frommain.js. - Create an
asyncfunction,getRandomNumber, that returns a random number:
async function getRandomNumber() {
console.log('Getting random number.');
return Math.random();
} - Create an
asyncfunction,determineReadyToLaunch, that returnstrueif its first argument is greater than0.5:
async function deteremineReadyToLaunch(percentage) {
console.log('Determining...