Higher Order Flow Control – Synchronous



Higher Order Flow Control – Synchronous

0 0


jseverywhere

My notes and slides from my presentation on Oct 26, 2012

On Github jden / jseverywhere

Higher Order Flow Control

@leJDen

Jason Denizac

on github

Our apps spend a lot of time waiting. If we're smart, we'll make good use of time while we're waiting. Especially true in a server (web scale!), but also useful client side.
This is a much better experience - you can go enjoy a beverage and do whatever else until your table is ready.
Promises are like IOUs: they represent a value which will be available eventually, at some time in the future.
Promises are composable - you can string together a long line of them to create chains of application flow which will happen eventually - as soon as they're ready.

Promises aren't about making your code look pretty

(although they can help)

Synchronous

    
function (stuff) {
  if (!stuff) throw new Error(false);
  return true;
}
    
  

Asynchronous

function (stuff) {
  return promise(function () {
    if (!stuff) this.reject(new Error(false));
    this.resolve(true);
  })
}
    

return ⇔ resolve

throw ⇔ reject

Promise States

Composable

f ◦ g (x) - arithmetic

f(g(x)) - synchronous code

g(x).then(f) - promises

Errors Bubble Up

users.getUsers({id: 2}, function (err, data) {
  if (err) {
    // ?
  }
  console.log(data);
})
    
try{
  users.getUsers({id: 2}, function (err, data) {
    if (err) {
      var newErr = new Error('Unable to load user 2');
      newErr.innerError = err;
      throw newErr;
    }
    console.log(data);
  })
} catch (err) {
  console.log('Oh no, there was an error:', err);
}
    
  users.getUsers({id: 2}).then(
  function (data) {
    console.log(data);
  },
  function (err) {
    console.log('Oh no, there was an error:', err);
  })
    
  users.getUsers({id: 2}).then(
  function (data) {
    console.log(data);
  })
  .then(manipulateSomeData)
  .then(saveSomeData)
  .then(null, function (err) {
    console.log('Oh no, there was an error:', err);
  })
    

Now, why should we care?

write clean code

seperation of concerns: define the interface

I need x, I do y

I don't care when

control flow is a separate concern

cross-cutting concerns

  • Operational
    • logging
    • auditing
    • analytics
  • Data
    • validation
    • crypto
    • cacheing
  • Policy
    • authorization
    • feature flags
    • policy injection

Resources

make amazing things

http://jden.us/jseverywhere

@leJDen