IN THEORY AND REALITY
"Why stop at lists! Promises in a box! Promises with a fox! Attributes are promises! Arrays are promises! Everything is a promise!"
doSomething().then(doSomethingAfter);
function foo(bar){
try{
var result = bar.toLowerCase();
return Promise.resolve(result);
}
catch(error){
return Promise.reject(error);
}
}
var loadFoo = foo('THE FUTURE');
loadFoo.then(function(result){
console.log(result);
});
function foo(){
return Promise.resolve('bar');
};
foo().then(function(result){
return result.toUpperCase();
})
.then(function(result){
return result.replace('R', 'T');
})
.then(function(result){
console.log(result);
});
function serveDrink(order, callback){
findBottle(order, function(bottle){
openBottle(bottle, function(){
findGlass(function(glass){
fillGlass(glass, bottle, function(drink){
giveToCustomer(drink, function(){
callback();
});
});
});
});
});
}
findBottle(order)
.then(openBottle)
.then(findGlass)
.then(fillGlass)
.then(giveToCustomer);
function serveDrink(order, callback){
findBottle(order, function(err, bottle){
if(err) handleError(err);
openBottle(bottle, function(err){
if(err) handleError(err);
...
});
});
}
findBottle(order)
.then(openBottle)
.then(findGlass)
.then(fillGlass)
.then(giveToCustomer, handleError);
var count = 0;
var onFinished = function(finishedFunc){
count++;
if(count == 2){
finishedFunc();
};
};
var order1 = serveDrink('rum', onFinished);
var order2 = serveDrink('vodka', onFinished);
var order1 = serveDrink('rum');
var order2 = serveDrink('vodka');
Promise.all([order1, order2]).then(finishedFunc);
Logger.prototype.logResult = function(promise){
return promise.then(function(result){
console.log(result);
}
}
var updateName = API.updateName('will');
updateName.fail(function(reason){
var errorCode = reason.status;
if(errorCode == 400){
handleFormError(reason.responseText);
}
else if (errorCode == 403){
handleUnauthorisedUser(reason.responseText);
}
else if (errorCode == 500{
handleServerError(reason.responseText);
}
else {
// Success
}
});
var updateName = API.updateName('will');
updateName.handle([400], handleFormError);
updateName.handle([401, 403], handleUnauthorisedUser);
updateName.handle('5XX', handleServerError);
updateName.done(function(){
// Success
});