Reliable and Recognized JavaScript Certification Online #

Promise

Promise in JavaScript represent eventual result (success or failure) of an asynchronous operation.
Before promises were introduced in ECMAScript 2015, asynchronous calls were handled by callback functions. Promises provide a simpler and cleaner way for handling asynchronous operations than callback-based method.
They also can be used to handle asynchronous errors in a way similar to synchronous try/catch statement.

Promise can be in one of these states:

  • pending – it is initial state, asynchronous operation has not completed yet and result is unknown,
  • fulfilled – operation completed in success,
  • rejected – operation failed.

When a promise is pending it can change to fulfilled or rejected state. Once a promise is fulfilled or rejected it is settled and cannot change its state again.

Creating promise

When you create a promise, you defines a work to do and conditions what does it mean success and failure.
To create a promise object use the Promise constructor. The syntax is as follow:

var promise = new Promise(function(resolve, reject) {
  // do a work, most likely asynchronous

  if (/* successful operation */) {
    resolve('success');
  }
  else {
    reject('failure');
  }
});

The Promise constructor takes one argument, a callback function called the executor.
The executor function is executed automatically when the promise is created It is done before the constructor returns the created object. It takes two arguments the resolve and the reject callback functions.
Usually the executor does some asynchronous work. When it is successfully completed it calls the resolve function. Otherwise when an error occurred it calls the reject function.

Promise example

Promise allow the method that performs the asynchronous task to return the value as a synchronous method. Instead of returning the final value immediately, the method returns promises to provide the value after a certain time, when the asynchronous task is completed.

function getImagePromise(url) {
    var promise = new Promise(function(resolve, reject) {
        var request = new XMLHttpRequest();
        request.open('GET', url);
        request.responseType = 'blob';
        request.onload = function() {
            if (request.status === 200) {
              resolve(request.response);
            } else {
              reject(Error('Image load failure:' + request.statusText));
            }
        };
        request.send();
    });
    return promise;
}

Using promise

You have to define what to do if there is a success by defining the resolve() function and what to do if there is a failure of some work by defining the reject() function.

The then() method of the Promise prototype you can use to define the resolve and the reject callback functions and to pass them to the promise.
The then() takes two arguments, the resolve handler and optional reject handler. It appends them to the promise and returns a new Promise object. The syntax is as follow:

promise.then(function(value) {
    // here you define what to do if the promise is fulfilled
}, function(error) {
    // here you define what to do if the promise is rejected
});

The catch() method of the Promise prototype you can use to define the reject callback function and to pass it to the promise.
The catch() takes one argument, reject handler. It appends it to the promise and returns a new Promise object.
Instead of passing both callbacks to the then() method, you can use method chaining and the reject handler pass to the catch() method. The syntax is as follow:

promise.then(function(value) {
    // here you define what to do if the promise is fulfilled
}).catch(function(error) {
    // here you define what to do if the promise is rejected
});

The finally() method of the Promise prototype appends a handler to the promise, which is called when the promise is settled. It returns a new Promise object.

promise.then(function(value) {
    // here you define what to do if the promise is fulfilled
}).catch(function(error) {
    // here you define what to do if the promise is rejected
}).finally(function(error) {
    // here you define what to do when the promise is settled
});

Using promise example

var imagePromise = getImagePromise('red_rose.png')
imagePromise.then(function(response) {
    var body = document.querySelector('body');
    var img = document.createElement('img');
    img.src = window.URL.createObjectURL(response);
    body.appendChild(img);
    console.log('Success');
}).catch(function(error) { 
    console.log('Failure')
    console.log(error);
}).finally(function() { 
    console.log('Done');
});

No Comments

Reply