Awaiting the result of async functions
In the previous recipe, we saw how to use async to create functions that resolve promises. However, we used the Promise API then callback to wait for the result. In many situations, we can use the await key word to wait for these values. It gets the job done, but there is a cleaner way to retrieve results from asynchronous functions.
This recipe demonstrates how to use await in order to return the result of a long-running operation.
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
4-02-await-async-results. - Copy or create an
index.htmlthat loads and runs amainfunction frommain.js.
- Create a
main.jswith anasyncfunction namedÂgetRandomNumberthat returns a random number:
// main.js
async function getRandomNumber () {
return...