- Suppose a program consisting of 3 distinct tasks
- Tasks are performed one at a time
- Always in a defined order
- Simplest style of programming
// Event loop pseudo code for(;;) { if (endOfProgram) quit(); if(eventToHandle) { // task waiting, task finished ... handleEvent(eventToHandle); // Callback } }
task1(function task2(task1Result) { // do something with task 1 result }) var task1 = function(callback) { result = longRunningTask(); // Blocking call callback(result); // Calling a passed callback }
$('#button').click(function () { askForTwitterHandle(function(twitterHandle) { twitterHandle.getTweets(function (tweets) { processTweets(function (processedTweets) { ui.show(processedTweets); }); }); }); });
$('#button').click(function () { askForTwitterHandle(function(twitterHandle) { twitterHandle.getTweets(function (tweets) { ... }); }, function onFailure(error) { handleError(error); }); });
try { handle = askForTwitterHandle(); tweets = handle.getTweets(); ... } catch (errorMessage) { console.log('I messed up'); }
ajax('template.html', function(err, template) { if (err) handleError(); render(template); }) // Becomes var promiseForTemplate = $http.get('template.html'); promiseForTemplate.then(render, handleError)
promiseForTemplate.then(onFulfilled, onFailed);
// var transformedPromise = promiseForTemplate.then(onFulfilled, onFailed);
var user = getUser(); // blocking, ie, prompt for password var username = user.name;
var userNamePromise = getUser().then(function (user){ return user.name; })
var user = getUser(); // blocking, ie, prompt for password if (user === null) throw new Error('null user');
var userPromise = getUser().then(function (user){ if (user === null) throw new Error('null user'); return user; })
try { updateUser(data); } catch (exp) { console.log('There was an error', exp); }
var updateUserPromise = updateUser(data).then(undefined, function(exp) { console.log('There was an error', exp); })
getUser('spike', function(err, user){ if(err) { ui.error(err); } else { getBestFriend(user, function(err, friend){ if (err) { ui.error(err); } else { ui.showBestFriend(friend, function(err, friend){ if (err) { ui.error(err); } }) } }) } })
getUser() .then(getBestFriend) .then(ui.showBestFriend) .then(undefined, ui.error)
Q library
.controller('testCtrl', function($scope, $q) { // inject the service var promiseOfTask = function () { var deferredTask = $q.defer(); // create a deferred object var result = blockingTask(); // long running task deferredTask.resolve(result) // resolve the future promise with the result return deferredTask.promise // return the promise } //using the promise promiseOfTask().then(function(result){ $scope.updateSomeModel(result); }) })
commonJS Promises/A
Python Twisted & Deferreds
Generators in Javascript