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.htmlthat loads and runs amainfunction frommain.js. - Create a
main.jsfile 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...