Laziness, Isolation,

and Predictability

THUNK

function incrementCustom(shouldIncrement) {
  return (dispatch, getState) => {
    const { counter } = getState()

    if (shouldIncrement(counter)) {
       dispatch(increment())
    }
 
    return null;
  }
}

const incrementIfEven = incrementCustom(c => c % 2 === 0);
const incrementIfSmall = incrementCustom(c => c < 100);
incrementIfEven();
incrementIfSmall();

incrementCustom(c => c % 2 !== 0)();

Task

/* App 1: impure */

const promise: Promise<string> = fetch('www.api.com/entityList');



async function main() {
  const data = await promise;
}


/** App 2: pure **/
const makePromise: () => Promise<string> = fetch('www.api.com/entityList');


async function main() {
  const data = await makePromise();
}

Formalising

/** App 2: pure **/
const fetchEntityTask: Promise<Entity[]> = () => fetch('www.api.com/entityList');


async function main() {
  const data = await fetchEntityTask();
}


/** customising behavior before execution; how it works at clarifai **/
const fetchModels = (appId) => () => = fetch(`www.api.com/apps/${appId}/models`);

async function main({ appId }) {
  const fetchCurrentModels: () => Promise<Model[]> = fetchEntityTask(appId);

  const modelListPromise: Promise<Model[]> = fetchCurrentModels();
  
  const modelList: Model[] = await modelListPromise;
 
  const modelListDuplicate = await fetchModels(appId)();

}

Rethinking Async Programming

function* mySaga() {
  const items = yield select(store => store.items);
  // PURE
  const effectList = items.map(
    i => call(fetchItemDataAndUpdateStoreSaga, i.id
  );
  
  // Actual call
  const resultList = yield all(effectList);
  
  /****
     do some more async stuff based on resultList
   ***/
  
  
  // if sequentially:
  for (const item of items) {
    yield call(fetchItemDataAndUpdateStoreSaga, i.id);
  }
  
}

Laziness, Isolation,

By Aviral Kulshreshtha