Creating and waiting for Promises
Promises provide a way to compose and combine asynchronous functions in an organized and easier to read way. This recipe demonstrates a very basic usage of promises.
Getting ready
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.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder namedÂ
03-01-creating-and-waiting-for-promises
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
. - Create a
main.js
file that creates a promise and logs messages before and after the promise is created, as well as while the promise is executing and after it has been resolved:
// main.js export function main () { console.log('Before promise created'); new Promise(function (resolve) { console.log('Executing promise'); resolve(); }).then(function () { console.log('Finished...