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

Yield

 Yield

Lightning talk.
How Generators and Co can make asynchronous code look better.
Where to use it - from Co to Koa.

krzychukula

October 29, 2015
Tweet

More Decks by krzychukula

Other Decks in Programming

Transcript

  1. yield
    @krzychukula

    View Slide

  2. function(){
    getUsername(function(err, username){
    getUser(username, function(err, user){
    //use username and user
    })
    })
    }

    View Slide

  3. function(){
    getUsername()
    .then(function (username) {
    return [username, getUser(username)];
    })
    .spread(function (username, user) {
    //use username and user
    });
    }

    View Slide

  4. co(function *(){
    var username = yield getUsername()
    var user = yield getUser(username)
    //use username and user
    })

    View Slide

  5. View Slide

  6. Generators

    View Slide

  7. Co

    View Slide

  8. View Slide

  9. co(function *(){
    var username = yield getUsername()
    var user = yield getUser(username)
    //use username and user
    })

    View Slide

  10. co(function *(){
    var username = “janek”
    var user = yield getUser(username)
    //use username and user
    })

    View Slide

  11. co(function *(){
    var username = “janek”
    var user = {id:”123”}
    //use username and user
    })

    View Slide

  12. Koa

    View Slide

  13. var koa = require('koa');
    var app = koa();
    app.use(function *(){
    this.body = 'Hello World';
    });
    app.listen(3000);

    View Slide

  14. function *list() {
    var res = yield books.find({});
    this.body = res;
    }

    View Slide

  15. nvm install v4

    View Slide

  16. Play with it!

    View Slide

  17. Thanks!
    krzychukula.blogspot.com

    View Slide