Last Updated: February 25, 2016
·
741
· 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');
  }
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside