$q

Paweł Pierzchała @zwrozka

Callbacks


ajaxRequest('GET', '/foo', function(success) {
  console.log('Success: ' + success);
}, function(error) {
  console.log('Error: ' + error);
});
          

Pyramid of doom


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

Promises


Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
    // Do something with value4
})
.catch(function (error) {
    // Handle any error from all above steps
})
.done();
          

Resolve


function onSuccess(success) { console.log("Success: " + success); }
function onError(error) { console.log("Error: " + error); }

promise = new Promise();
promise.then(onSuccess, onError);

promise.resolve("Foo")
// => Sucess: Foo
          

Reject


function onSuccess(success) { console.log("Success: " + success); }
function onError(error) { console.log("Error: " + error); }

promise = new Promise();
promise.then(onSuccess, onError);

promise.reject("Foo")
// => Error: Foo
          

Error propagation


function onSuccess(success) { console.log("Success: " + success); }
function onError(error) { console.log("Error: " + error); }

promise = new Promise();
promise.then(onSuccess)
       .then(onSuccess)
       .then(onSuccess, onError);

promise.reject("Foo")
// => Error: Foo
          

Exercise

Implement simple promises

wrozka/promises