Slide 1

Slide 1 text

ES5 . ES6 . ES7 Asynchronous JavaScript

Slide 2

Slide 2 text

Callbacks Promises Async/Await Generators

Slide 3

Slide 3 text

Callbacks - ES5 Example 1: function handler(request, response) { User.get(request.user, function(err, user) { if (err) { response.send(err); } else { Notebook.get(user.notebook, function(err, notebook) { if (err) { return response.send(err); } else { doSomethingAsync(user, notebook, function(err, result) { if (err) { response.send(err); } else { response.send(result); } }); } }); } }); }

Slide 4

Slide 4 text

Callbacks - ES5 Example 2: require('request') .get('http://www.google.com', function(err, response) { if (err) { console.error(err); } else { require('fs') .writeFile('google.html', response.body, function(err) { if (err) { console.error(err); } else { console.log('wrote file'); } }); } });

Slide 5

Slide 5 text

Promises - ES6 Example 2: require('request-promise') .get('http://www.google.com') .then((response) => { return require('fs-promise').writeFile('google.html', response); }) .then(() => { console.log('wrote file'); }) .catch((err) => { console.log(err); });

Slide 6

Slide 6 text

Promises - ES6 Example 1: function(request, response) { let user, notebook; User.get(request.user) .then((aUser) => { user = aUser; return Notebook.get(user.notebook); }) .then((aNotebook) => { notebook = aNotebook; return doSomethingAsync(user, notebook); }) .then((result) => { response.send(result); }) .catch((err) => { response.send(err); }); }

Slide 7

Slide 7 text

Async/Await - ES7 Descrip(on When async func,on is called, it returns a promise. When the async func,on returns a value, the promise will be resolved with the returned value. When the async func,on throws an excep,on or some value, the promise will be rejected with the thrown value. Async func)on can contain await expression, that pauses the execu)on of the async func)on and waits for the passed promise's resolu)on, and resumes the async func)on's execu)on and returns the resolved value.

Slide 8

Slide 8 text

Async/Await - ES7 A Simple Example function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function add1(x) { let a = resolveAfter2Seconds(20); let b = resolveAfter2Seconds(30); return x + await a + await b; } add1(10).then(v => { console.log(v); // prints 60 after 2 seconds. });

Slide 9

Slide 9 text

Async/Await - ES7 A Slight Tweak function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function add2(x) { let a = await resolveAfter2Seconds(20); let b = await resolveAfter2Seconds(30); return x + a + b; } add2(10).then(v => { console.log(v); // prints 60 after 4 seconds. });

Slide 10

Slide 10 text

Async/Await - ES7 Let's get back to the previous example. Example 1: async function something(request, response) { try { let user = await User.get(request.user); let notebook = await Notebook.get(user.notebook); let result = await doSomethingAsync(user, notebook); response.send(result); } catch(err) { response.send(err); } }

Slide 11

Slide 11 text

Async/Await - ES7 What does async do? Essen%ally, it wraps the return value of the func%on in a promise. Under the hood it is more or less using generators, but all of that is hidden away behind this simple syntax. await "Hello!" What if it's a non-promise? Will this work?

Slide 12

Slide 12 text

Generators - ES6 Generators are func-ons which can be exited and later re-entered. Their context (le-able bindings) will be saved across re-entrances. Syntax function* name([param[, param[, ... param]]]) { statements }

Slide 13

Slide 13 text

Generators - ES6 Calling a generator func/on does not execute its body immediately; an iterator object for the func/on is returned instead. When the iterator's next() method is called, the generator func/on's body is executed un/l the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator func/on.

Slide 14

Slide 14 text

Generators - ES6 A Simple Example function* idMaker(){ let index = 0; while(index < 3) yield index++; } let gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // undefined

Slide 15

Slide 15 text

Generators - ES6 Another Example function* anotherGenerator(i) { yield i + 1; yield i + 2; yield i + 3; } function* generator(i){ yield i; yield* anotherGenerator(i); yield i + 10; } let gen = generator(10); console.log(gen.next().value); // 10 console.log(gen.next().value); // 11 console.log(gen.next().value); // 12 console.log(gen.next().value); // 13 console.log(gen.next().value); // 20

Slide 16

Slide 16 text

Generators - ES6 Generators are mostly used with promises. { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident", "body": "suscipit recusandae consequuntur expedita" } const co = require('co'); const fetch = require('node-fetch'); co(function* (){ let uri = 'https://jsonplaceholder.typicode.com/posts/1'; let response = yield fetch(uri); let post = yield response.json(); console.log('Title: ', post.title); // sunt aut facere repellat provident });

Slide 17

Slide 17 text

How to start using Async/Await? h"p:/ /babeljs.io // .babelrc { "presets": ["es2015", "es2017"] }

Slide 18

Slide 18 text

And a lot of study. • Handle asynchronous non-blocking I/O in JavaScript • Iterators and Generators • Async Func@on • From Callbacks to Promises to Generators to Async/await • The Hidden Power of ES6 Generators • Generators in JavaScript [Video] • Async Programming in ES7 [Video]

Slide 19

Slide 19 text

Hopefully, this didn't blow your mind.

Slide 20

Slide 20 text

Thank You