Javascript

Promises

@tkssharma

UnitedHealth Group

Delhi,India

  • What is asynchronous code?
  • How to write async code in JS?
  • Why promises?
  • History
  • Promises in JavaScript
  • Promises Now
  • Promises in your code
  • Generators / Yields (ES6)
  • Async / Await (ES7)

HOW TO WRITE ASYNC CODE

  • Event Loop
  • Callbacks
  • Promise
  • Generators
var promise = new Promise(function (resolve, reject) {
    setTimeout(function () { 
        resolve();
        console.log('Promise resolved');
    }, 5000);
});

var deferred = $.Deferred();
setTimeout(function () { 
    deferred.resolve();
    console.log('Deferred resolved');
}, 10000);

Promise.all([promise,deferred]).then(function () {
    console.log('All is done');
});
 function getMyPhoto(tag, handlerCallback) {
    asyncGet('login_url', function () {
        asyncGet('photo_url', function() {
            asyncGet('photo_details', function(neededResult) {
                handlerCallback(neededResult);
            });
        });
    });
}

getMyPhoto('puppy', drawOnScreen);

Callback Hell

  • DOM Promises
  • ECMAScript 6 Promises
  • Promises/A
  • Promises/A+
  • Promises/Kiss
  • jQuery Deferred
  • Other
loadSomething().then(function(something) {
    loadAnotherthing().then(function(another) {
    DoSomethingOnThem(something, another);
    });
});

Nested promise

q.all([loadSomething(), loadAnotherThing()])
    .spread(function(something, another) {
        DoSomethingOnThem(something, another);
});

Let's Fix Nested promise

function anAsyncCall() {
    var promise = doSomethingAsync();
    promise.then(function() {
        somethingComplicated();
    });
    
    return promise;
}

Broken Promise Chain

function anAsyncCall() {
    var promise = doSomethingAsync();
    return promise.then(function() {
        somethingComplicated()
    });   
}

Fix for Broken Promise Chain

function workMyCollection(arr) {
    var resultArr = [];
    function _recursive(idx) {
        if (idx >= resultArr.length) return resultArr;
            
        return doSomethingAsync(arr[idx]).then(function(res) {
            resultArr.push(res);
            return _recursive(idx + 1);
        });
    }

    return _recursive(0);
}

Async Operation on Array

function workMyCollection(arr) {
    return q.all(arr.map(function(item) {
        return doSomethingAsync(item);
    }));    
}

Fix code for Async Operation on Array Using Map

var promise;
if (asyncCallNeeded) 
    promise = doSomethingAsync();
else
    promise = Q.resolve(42);
        
promise.then(function() {
    doSomethingCool();
});

Ghost promise

Q(asyncCallNeeded ? doSomethingAsync() : 42)
    .then(
        function(value){
            doSomethingGood();
        })
    .catch( 
        function(err) {
            handleTheError();
        });

Fix for Ghost promise

Promises Observables 0.0

By tkssharma

Promises Observables 0.0

Lightning talk about AngularJS 2.0

  • 820