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

Asynchronous JavaScript

Asynchronous JavaScript

Asynchronous JavaScript (Internal Talk at Leapfrog Technology)

* From ES5 to ES6 to ES7
* Callbacks
* Promises
* Generators
* Async/Await

Saugat Acharya

December 19, 2016
Tweet

More Decks by Saugat Acharya

Other Decks in Programming

Transcript

  1. 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); } }); } }); } }); }
  2. 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'); } }); } });
  3. 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); });
  4. 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); }); }
  5. 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.
  6. 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. });
  7. 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. });
  8. 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); } }
  9. 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?
  10. 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 }
  11. 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.
  12. 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
  13. 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
  14. 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 });
  15. 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]