Espera un poco,

un poquiiiiiito máaaas...

BeerJS Córdoba
Agosto 2018

(Una introducción de telenovela

a la programación asincrónica

en JavaScript)

#JavaScriptFundamentals

Joel A. Villarreal Bertoldi

¿Por qué esperar?

Sincrónico

vs.

Asincrónico

Todas las instrucciones se ejecutan sucesivamente, una luego de la otra.

Sincrónico

vs.

Asincrónico

Todas las instrucciones se ejecutan sucesivamente, pero algunas pueden completarse en un futuro.

Podemos esperar a que algo
pase de distintas maneras.

Callbacks (browser)

$.getJSON('/my/data.json', {
  success: function () {
    // Yay!
  },
  error: function () {
    // :(
  }
});

// Life goes on...

Callbacks (node)

const fs = require('fs');

fs.readFile('/foo/bar', function (file) {
  // Hello callback!
});

fs.writeFile('/foo/bar', data, function () {
  // Problem?
});

Callback

/**
 * Una función A recibe como argumento
 * otra función B que será llamada
 * cuando A lo determine.
 **/

myFunc('foo', cb);

Callback hell

doSomething(data, function (results) {
  nextProcess(results, function (parsedData) {
    yetAnotherAction(parsedData, function (processed) {
      oneMoreAndFinished(processed, function (polished) {
        finish(polished, function (finished) {
          // Phew...
        });
      });
    });
  });
});

Promises

const axios = require('axios');

axios
  .get('/foo')
  .then(success)    // Yay!
  .catch(failure);  // :(

Promises

const axios = require('axios');

axios.get('/foo')
  .then(yayGet)
  .catch(booGet);

axios.post('/bar', { foo: 'foo!' })
  .then(yayPost)
  .catch(booPost);

¿Qué va a suceder primero?

?

Nested Promises?

const axios = require('axios');

axios.get('/foo')
  .then((data) => {
    axios.post('/bar', data)
      .then(yayPost)
      .catch(booPost);
  })
  .catch(booGet);

Promise "little hell"

const axios = require('axios');

axios.get('/foo')
  .then(data => axios.post('/bar', data))
  .then(response => axios.patch('/fiz', response))
  .then(magic => axios.delete('/magic', magic))
  .then(data => axios.post('/bar2', data))
  .then(response => axios.patch('/fiz2', response))
  .then(magic => axios.delete('/magic2', magic))
  .catch(boom);

Promise's Anatomy

const doHeavyAction = 
  (foo) => new Promise((resolve, reject) => {
    try {
      const bar = doSomethingComplicated(foo);
      resolve(bar);
    } catch (e) {
      reject(e);
    }
  });

doHeavyAction()
  .then(bar => console.log(bar));
  .catch(e => console.warn(e));

:)

:(

Esperando promesas

const dinnerActions = [
  chopVegetables,
  prepareWok,
  seasonFood,
  getWine,
  putTable
];

Promise.all(...actions)
  .then(result => shout("DINNER'S READY!"));
  .catch(result => callForPizza);

Promise[]

(porque podemos prender fuego la cocina, ¿vio?)

map, reduce ...

array magic!

Sincronizando lo asíncrono

class SinglePersonWhoCooks {
  async prepareVeggieWok() {
    try {
      await this.chopVegetables();
      await this.prepareWok();
      await this.seasonFood();
      await this.getWine();
      await this.putTable();
      return this.shoutReady();
    } catch (problem) {
      return this.callForPizza();
    }
  }
}

async/await

¿Qué conviene usar entonces?

Callbacks no.

¿Promises, async/await?

La verdad de la milanesa es...

...lo que consideres más legible, para que de acá a unos meses, entiendas qué quisiste escribir en tu código.

¿?

Espera un poco,

un poquiiiiiito máaaas...

BeerJS Córdoba
Agosto 2018

(Una introducción de telenovela

a la programación asincrónica

en JavaScript)

#JavaScriptFundamentals

¡Gracias! :)

"Espera un poco... un poquito más..."

By Joel Alejandro Villarreal Bertoldi

"Espera un poco... un poquito más..."

Charla sobre callbacks, Promises y async/await para la BeerJS Córdoba del 16/08/2018.

  • 806