Web Developer Interview Preparation

Promises

Definition Promises are JavaScript objects that describe what is supposed to happen when an asynchronous operation takes place. They provide certain guarantees and structure to help callbacks and make a time-based operation easy to use. If you want to know about callback function, check out my previous post. [LINK] There are some problems with callbacks because results of callbacks rely on a condition of the network. Therefore, callbacks often suffer from clarity and a lack of guarantees. So, we need promises to guarantee an execution. Here are important features for promises, which are resolve( ), reject( ), and then statement. With resolve( ), we specify what will happen when all our requests will work. And reject( ), we specify what we want to execute when our request doesn’t work. then statement is a special method that will execute when the promise is work correctly. Let’s take a look at the following example.

var isHeeyaMotivated = true;
// Promise
var isHeeyaAchievetheGoal = new Promise {
function (resolve, reject) {
    if (isHeeyaMotivated) {
        var goal = {
            task: 'Graphicdesign',
            topic: 'mainscreen'
    };
    resolve(goal);
    } else {
        var reason = new Error('heeya is not happy.');
    reject(reason);
    }
  }
);
// call the promise
var askHeeya = function() {
    isHeeyaAhievetheGoal.
        .then(function (fulfilled) {
            console.log(fulfilled);
        })
        .catch(function (error) {
            console.log(error.message);
        });
}
askHeeya();
So, this is how promises work. When we want to do something after something happens, we create a promise. Once the promise resolves, it is going to do whatever we specify in the then statement. We can also make a chain of promises.

var reportHunya = function(goal) {
    return new Promise(
        function (resolve, reject) {
            var message = 'Hi Hunya, I have achieved ' + goal.task + ' for' + goal.topic
            resolve(message);
        }
   );
};
If something happens to the promise and it does not execute, the chain promise will not be executed. It is always better to be specific to what happens when the promise is fulfilled, and what happens if it is rejected. Reference What is the relationship between promises and callbacks? Mastering Web developer Interview Code – Ray Villalobos, Lynda.com [LINK] ]]>

Leave a Reply

Your email address will not be published. Required fields are marked *