Oubliez les migraines, faites de
l'asynchrone... synchrone !

Jordane Grenat @JoGrenat

Promises

   
myAsyncCall()  
  .then(data => console.log(data))  
  .catch(err => console.error(err));
                        

Promises & Chaining

   
myAsyncCall()  
  .then(data => data.user)  
  .then(user => console.log(user));
                        

Promises & Chaining with... Promises !

   
myAsyncCall()  
  .then(userId => getUserAsync(userId))  
  .then(user => console.log(user))
  .catch(error => console.error(error));
                        

Promises in parallel

   
Promise.all([promise1, promise2])
  .then(data => {
    console.log(data[0], data[1]);
  });
                        

Generators

   
function *myGenerator() {  
  yield 1;  
  yield 2;
}
                        

const it = myGenerator();
console.log(it.next().value); // 1
console.log(it.next().value); // 2
                        

2-way communication

   
function *myGenerator() {  
    const value = yield 1;  
    yield 2;
    yield value;
}
                        

const it = myGenerator();
console.log(it.next().value); // 1
console.log(it.next('Hello').value); // 2
console.log(it.next().value); // 'Hello'
                        

2-way communication with errors

   
function *myGenerator() {  
  try {
    yield 1;
  } catch(err) {
    console.error(`Error: ${err}`);
  }
}
                        

const it = myGenerator();
console.log(it.next().value); // 1 
it.throw('SomeError'); // Error: SomeError
                        

Generators and Promises

   
function *myGenerator() {  
  const user = yield getUserAsync();
  console.log(user);
}
                        

const it = myGenerator();
const promise = it.next().value;
promise.then(it.next); // show user
                        

Generators and Promises with Coroutines

   
co(function*() {  
  const user = yield getUserAsync();
  console.log(user);
});
                        

Async functions

   
async function myFunction() {  
  const user = await getUserAsync();
  console.log(user);
}

myFunction();
                        

Stade 3: not in ES2016

Observables

   
const source = Observable
    .fromEvent(button, 'click');
    
source.subscribe(event => {
  console.log('Someone clicked!', event);
});
                        

Stade 1... but usable with RxJS

Thanks you!

Jordane Grenat @JoGrenat