My JS Journey: Promises

Promises

There are a lot of ES6 features that are not supported in ES5 browsers. Promises are among them. Your ES6 code may or may not work based on which Node.js or WebPack you are using, which browser version it is rendering in, etc. Here is a comprehensive chart that shows which features are supported in which environments. Here’s another more detailed one specific to Node.js.

Although Promises are supported by the most current versions of WebPack, babel-core and Node.js, in the past, babel-polyfill was a separate requirement. If you find that adding the Promise code doesn’t work, first update your WebPack or Node.js, or try installing polyfill. Its purpose is to add to the global scope as well as native prototypes like String to enable use of new built-ins until they are added to the core packages. For more information, read how it works here.

install --save babel-polyfill

For this example, I will show how to add a promise to my ES6 CLI Skeleton.

Get the Skeleton

If you have not already followed the instructions to create the ES6 CLI Skeleton, you should do that now (or follow the instructions for Forking that I will include in another blog soon). If you know how to copy one of your GitHub repositories, clone it, then skip this section.

Clone the Project

In GitHub:

Navigate to your CLI Skeleton.
On the right side, click the green Clone or Download button.
Copy the URL.

In the console:

Navigate to the directory where you want the project directory to exist.
Run the following command:

git clone https://github.com/YourRepo/skeleton-cli-js.git

Output:

Cloning into 'skeleton-cli-js'...
remote: Counting objects: 21, done.
remote: Compressing objects: 100% (11/11), done.
remote: Total 21 (delta 4), reused 21 (delta 4), pack-reused 0
Unpacking objects: 100% (21/21), done.
Checking connectivity... done.

Navigate to skeleton-cli-js (the project directory).
Run this command:

git remote show origin

Output:
remote origin
Fetch URL: https://github.com/RidgewellServices/skeleton-cli-js.git
Push URL: https://github.com/RidgewellServices/skeleton-cli-js.git
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master rebases onto remote master
Local ref configured for 'git push':
master pushes to master (up to date)

If you plan to submit pull requests to augment a repository, this is fine. Otherwise, to create your own project, but keep all the history from the original project, run the following commands.

This command disassociates the code from the original repository.

git remote remove origin

Create a new repository on GitHub, then run the next command to
associate the code with your new repository.

git remote add origin https://github.com/YourGitHub/your-new-repo.git

Now, when you show the origin, you are pointed to your new repo. In the project directory, run:

git remote show origin

Output:
remote origin
Fetch URL: https://github.com/YourGitHub/your-new-repo.git
Push URL: https://github.com/YourGitHub/your-new-repo.git
HEAD branch: (unknown)

When you checkin, it will go to your repository.
To install the package dependencies, from the command line, run:

npm install

Then, build to ensure everything is working:

npm run build

And, finally, run the code:

npm start

It should say “Hello.”

Add a Promise

Promises let you ensure the order of asynchronous events, such as file reading. In my example, I retrieve text after a timeout. It’s contrived, but it shows how a promise works.

Add Promises

Change the app code by adding some promises. Change src/hello.js as follows:

const getWorld = () => new Promise((resolve) => {
  setTimeout(() => resolve(' world'), 500);
});

const hello = () => new Promise((resolve) => {
  getWorld().then(result => {
    resolve('hello' + result);
  });
});

export default hello;

Change src/index.js to resolve the Promise, as follows:

import hello from './hello';

const sayHello = (message) => {
  console.log(message);
};

function main() {
    var args = process.argv;
    if (args[2] && args[2] === '--v' ) {
        console.log('Es6CliSkeleton - version 1.0.0');
    } else {
        hello().then(res => sayHello(res));
    }
}

main();

In the project directory, run:

npm run build

In the project directory, run:

npm start

Output:
node dist/index
hello world

If you want to do the same thing in the browser, download my ES6 Browser Skeleton instead. Change src/hello.js as above. Then, modify src/index.js to resolve the Promise, as follows:

import hello from './hello.js';

const sayHello = (message) => {
  document.getElementById("message").innerHTML = message;
};

document.getElementById('msgBtn').addEventListener('click', () => {
  hello()
  .then(res => sayHello(res));
});

Verify it works by building and refreshing index.html. It should say, “hello world.”

Check the code in.

In Conclusion

Promises in ES6 are not difficult, although they can be cumbersome if there are a lot of nested Promises. The new—and, as of yet, not completely supported—ES7 feature, async/await, is meant to simplify nested Promises. I’ll write about that in a future post. You can find the CLI Promise code in my github repository, promises.

Copyright ©2014-17 Ramona Ridgewell. All rights reserved.

Advertisements
This entry was posted in #Education, AmWriting, Coding, Education, JavaScript, Programming, Software Development, Writing and tagged , , , , , , . Bookmark the permalink.

2 Responses to My JS Journey: Promises

  1. Pingback: My JS Journey: A Promise in a Browser | RamonaRidgewell

  2. Pingback: Mocha as a JavaScript Test Framework | RamonaRidgewell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s