Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Actually Understanding Asynchronous JavaScript

Actually Understanding Asynchronous JavaScript

Steve Kinney

August 04, 2016
Tweet

More Decks by Steve Kinney

Other Decks in Technology

Transcript

  1. What constitutes "completion?" • Hitting the end of a function

    • Reaching a return statement • Throwing an error (and not catching it)
  2. The Call Stack A data structure that keeps track of

    where we are in the execution of our programs.
  3. var possessions = []; var lifeSavings = 25; function goGroceryShopping()

    { buyVeganHam(); } function buyVeganHam() { if (lifeSavings < 10) { throw new Error('Not enough money.'); } lifeSavings = lifeSavings - 10; possessions.push('vegan ham'); } goGroceryShopping();
  4. var possessions = []; var lifeSavings = 25; function goGroceryShopping()

    { buyOrganicAlmondMilk(); buyVeganHam(); } function buyOrganicAlmondMilk() { lifeSavings = lifeSavings - 20; possessions.push('organic almond milk'); } function buyVeganHam() { // When this code eventually executes, we'll only have $5 left. if (lifeSavings < 10) { throw new Error('Not enough money.'); } lifeSavings = lifeSavings - 10; possessions.push('vegan ham'); } goGroceryShopping();
  5. The Event Loop A programming construct that waits for and

    dispatches functions in the Event Queue to the Call Stack.
  6. setTimeout(function () { console.log('I will happen later.'); }, 5000); Timers

    setTimeout is available in all browsers and Node.js
  7. function callbackSandwich(callbackFunction) { console.log('Top piece of bread.'); if (typeof callbackFunction

    === 'function') callbackFunction(); console.log('Bottom piece of bread.'); } callbackSandwich(function () {console.log('American cheese.')}); callbackSandwich(); // Just two pieces of bread.
  8. asyncMultiply(2, 3).then(c => c * 1000).then(c => console.log(c)); Promise Chaining

    The return value of the previous link is passed to the next then() method.
  9. asyncMultiply(2, 3).then(c => c * 1000) .then(c => { throw

    new Error('KABOOM!') }) .catch(e => console.error(e));