Last Updated: February 25, 2016
·
363
· m93a

Avoiding callback hell

Have you ever wondered if it's possible to pause a function execution until a event fires? Well, in ES6 it is!

function listen(){
  var gen = suspend();
  var wait = function(){
    var done = 0;
    return (e)=>done||(done=1,gen.next());
  }
  gen.next();

  function* suspend(){
    //synchronous events?
    console.log('waiting for doc. load');
    yield window.addEventListener('load',wait());
    console.log('loaded, waiting for click');
    var click = yield document.addEventListener('click',wait());
    console.log('clicked');
  }
}