Async Generators

synchronous looking asynchronous code.

by bhupendra negi

JavaScript

function getAjaxData(str) {
  console.log("fetching..."+str);
  // next will resume it
setTimeout( () => myiterator.next(str) , 1000)

}

function *gen() {
  // yield will pause the js execution
  var x = yield getAjaxData("Hello");
  console.log(x);
  var y =  (yield getAjaxData("JOHN!"));
  console.log(y);
  var z =  (yield getAjaxData(x+y));
   console.log(z);
}

var myiterator = gen();
// to start the generator function do this
myiterator.next();
// now further resuming the generator will be done by setTimeout/ajax / asynnc task