Broad Network


Basics of Promise in ECMAScript 2015

Promise in ECMAScript 2015 – Part 1

ECMAScript 6

Foreword: In this tutorial, I illustrate the meaning of Promise in ECMAScript 2015.

By: Chrysanthus Date Published: 21 Jul 2016

Introduction

In this tutorial, I illustrate the meaning of Promise in ECMAScript 2015. When a script is run, the statements are executed one after another from top to bottom. That is synchronous behabior. On the other hand, it is possible to have say 10 statements in a script, and the fifth statement replaced by a code segment. If this code segment is Promise Production, it would execute at its own time (later), while the statements below it continue to run. That is asynchronous behavior.

The code that makes use of the promise production can be placed at the bottom of the script.

Illustration
Read and try the following script, where the promise production counts from 1 to 1000,000,000. The alert statement just after is executed before the counting goes through. The consumer code for the promise production is at the bottom of the script.

<script type="text/ecmascript">

    var promise = new Promise(
        function (resolve, reject)
            {
                var counter = 0;
                while (counter < 1000000000)
                    counter = counter + 1;

                if (counter == 1000000000)
                    {
                        resolve(counter); // success
                    }
                else
                    {
                        reject('Could not count!'); // failure
                    }
            });

    alert('seen');

    promise.then(
        function (value)
            {
                alert(`Counted up to ${value}.`);
            },
        function (reason)
            {
                alert(`Could not count up to ${reason}!`);
            }
    );

</script>

Syntax
Promise code consists of promise production and promise consumption. The syntax for Promise production is:

    promise = new Promise(callback);

where callback is a callback function and promise is a name of your choice. On the right of the assignement operator is the Promise constructor. The argument to the promise constructor is a callback function. This callback function is called by the consumption promise code (at the bottom); however, the production code works at its own time at its own pace.

The syntax for the callback function is:

        function (resolve, reject)
            {

                 // do a thing, possibly async, then…

                if (...)
                    {
                        resolve(value); // success
                    }
                else
                    {
                        reject(reason); // failure
                    }
            }

The function has two arguments: resolve and reject. resolve is a function call whose argument is the successfully result of the production code. reject is also a function call, but its argument is the error message if the productrion code fails. Either of the function simply sends its argument to the consumption code.

The body of the callback function is in two parts. The first part does what you want the production code to do, whenever it can do it. This first part must return a result: a number or a string or an array or a set or a map or any other kind of object.

The second part of the function body is a conditional if-else statement. If there is a result, the if-part is executed with resolve(result). If there is a failure the else-part is executed with reject(reason), an error message (or error object).

The syntax for the consumption code is:

    promise.then(onFulfilledFunction, onRejectedFunction);

There are two arguments: two callback functions. Here, promise is the object you created in the production. It has a method, then(), which calls the callback function of the production. The syntax for the then method is:

    promise.then(
        function (value)
            {
                 /* fulfillment */
            },
        function (reason)
            {
                /* rejection */
            }
    );

The first callback function here displays the result, otherwise the second displays the error message (handles the error).

A Good Use of the Promise Feature
The promise feature is good with networking. You can have a script with network code. You do not know when the network (server) will respond, but you what the statements below the network code to continue executing. In this case the nextwork code is the production code. The consumption code is placed somewhere down, in the script.

That is it for this part of the series.

Chrys

Related Links

ECMAScript Basics
ECMAScript Operators
Expressions in ECMAScript
Statements in ECMAScript
Custom Objects in ECMAScript
Functions in ECMAScript
ECMAScript Date Object
The ECMAScript String Object
ECMAScript String Regular Expressions
ECMAScript Template Literal
The ECMAScript Array
ECMAScript Sets and Maps
ECMAScript Number
Scopes in ECMAScript
Mastering the ECMAScript (JavaScript) eval Function
Sending Email with ECMAScript
ECMAScript Insecurities and Prevention
Advanced Course
Advanced ECMAScript Regular Expressions
Promise in ECMAScript 2015
Generator in ECMAScript 2015
ECMAScript Module
More Related Links
Node Mailsend
EMySQL API
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course

Comments

Become the Writer's Follower
Send the Writer a Message