A TacoBell™ Story

@_abhinavrastogi

PromiseS

What they are


Promises provide a well-defined interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.


Analogy: You want to eat a Taco at TacoBell. You give your order and pay at the cashier's desk. The cashier gives you a receipt and order number. You wait for your turn and you are called when the order is ready.
Object: The receipt/order number. It's an assurance you'll get your food.

Result of action: You getting your food

Async: Food takes time to prepare, they take other orders in the meantime.

What they Really mean



An easy way to avoid writing the callback Pyramid of Doom



Wait, EgyptiAns wrote JS?


Probably not... 
But this is also a Pyramid of Doom:

 step1(function (value1) {
    step2(value1, function(value2) {
        step3(value2, function(value3) {
            step4(value3, function(value4) {
                // Do something with value4
            });
        });
    });
});

Callbacks

(A Flashback)
  • A callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time.
  • A callback-hell is simply a heavily nested code, which makes it difficult to read and debug.
  • Anonymous functions are BAD if they do stand-alone, repeatable tasks.

A Better Definition



A Promise is an object representation of an event. 

In the course of its life, a Promise goes from a pending state, when it’s called, to a resolved or rejected state, when it’s been completed, or it could also stay pending forever and is never resolved.

Analogy: Once you have given your order at TacoBell, your order is in a pending state when created. When your food is ready, it is resolved. If some ingredient is not available, your order is rejected and you are informed. 'Pending Forever' is not realistic in a restaurant, but infinite loops are possible in code!

Whoosh.. over the head?


  • Basically, a promise is an object which takes a call to an asynchronous function and wraps it in a proxy which is called when the wrapped function completes or errors.
  • In other words, it provides an abstraction for representing the state of the async call.

Analogy: The receipt/order number is the proxy for your food. You (your order number) is called out when the food is ready. For the chef, the order and order number is all that matters. Not who ordered it. It is an abstraction.

Simple example


pStep1()
.then(pStep2)    // pStep2 gets called with the value returned by pStep1
.then(pStep3)    // similar thing happens here
.then(function(value4) {
    // do something with value4 here, 
    // which is the value returned by pStep3
})
.fail(function(err) {
    // handle error here
})
.finally(function() {
    // this is called in both cases
});

So, Why Promises?


What is this ABCD?


Whats the difference?


  • For that, you'll have to go through the specs. 
  • But basically, since its a feature which is currently in development, different people are coming up with their own specs which they think are best.
  • For eg. Promises/A+ clarifies the behavioral clauses of the earlier Promises/A proposal, extending it to cover de facto behaviors and omitting parts that are underspecified or problematic.
  • But Promises is an old concept... The term promise was proposed in 1976 by Daniel P. Friedman and David Wise

How to create a promise


KFC Method
 function oneZingerPlease(customFillings) {
    return Q.Promise(function(resolve, reject, notify) {
        var request = new zingerRequest(customFillings);
        
        request.onload = function() {
            if (request.status === 200) {
                resolve(request.yummyZinger);
            } else {
                reject("Chef is feeling sad.");
            }
        }
        
        request.onerror = function(err) {
            reject("Cant make burger because", err);
        }
        
        request.onprogress = function(event) {
            notify(event.loaded / event.total);
        }
    });
}

How to create a promise


TacoBell Method
 function oneTacoPlease(customFillings) {
    var request = new tacoRequest(customFillings);
    var deferred = Q.defer();

    request.onload = function() {
        if (request.status === 200) {
            deferred.resolve(request.yummyTaco);
        } else {
            deferred.reject("Chef is feeling sad.");
        }
    }

    request.onerror = function(err) {
        deferred.reject("Cant make taco because", err);
    }

    request.onprogress = function(event) {
        deferred.notify(event.loaded / event.total);
    }

    return deferred.promise;
}




DEMO




Thank you

Made with Slides.com