Javascript
Promises
@tkssharma
UnitedHealth Group
Delhi,India
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
RX JS Promises Observables 2.x
By tkssharma
RX JS Promises Observables 2.x
Lightning talk about AngularJS 2.0
- 829