Into Promises: a basic example

Gaetano Violante

Promises are an important JavaScript feature introduced by ES6, which helps the developers to implement asynchronous actions, and therefore more efficient web pages.

In this article I would like to provide a very basic example of Promises, so that you won’t feel insecure anymore to use them.

Let’s have a look together at the code.

The HTML consists of just a button element, and I’m going to use it to trigger the promise. When the promise complete its execution, the button text will be then updated, but after a delay, just to show the power of asynchronous actions.

The JavaScript consists of two functions. The first one is the GetPromiseDefinition, which basically only returns the promise object. The promise is resolved or rejected randomly, based on the current time seconds being an odd or even number. The second function is the CallPromise which will be used when the button is clicked. This function needs the promise definition itself, that’s why I’m calling the GetPromiseDefinition in here.

Here below the full code:

const c_RESOLVED = 'Promise resolved';
const c_REJECTED = 'Promise rejected';
const c_TRIGGERED = 'Promise triggered';

let GetPromiseDefinition = function () {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            let seconds = new Date().getSeconds();
            if (seconds % 2 === 0)
        }, 5000)
let CallPromise = function (element) {
    let promise = GetPromiseDefinition();

        .then(function (value_from_promise) { element.value = value_from_promise; })
        .catch(function (value_from_promise) { element.value = value_from_promise; })
    element.value = c_TRIGGERED;

<input type="button" value="Click here to call the promise" onclick="CallPromise(this)"/>

Two considerations:

  • The resolve / reject argument can be a complex object. In this case I did use only a string for sake of clearness.
  • Note the message “Promise has been triggered” appears before the promise returns the new value. This choice I made was to highlight the asynchronous action.

For a deep understanding I suggest this article.

Hope you enjoyed the reading!


you might also like