Generators

function* callMe() { yield '1'; yield '…and a 2'; yield '…and a 3'; return; yield 'this won’t print'; } var anAction = callMe(); console.log(anAction.next()); //=> { value: ‘1’, done: false } console.log(anAction.next()); //=> { value: ‘…and a 2’, done: false } console.log(anAction.next()); //=> { value: ‘…and a 3’, done: false } console.log(anAction.next()); //=> { value: ‘undefined’, done: true } console.log(anAction.next()); //=> { value: ‘undefined’, done: true } // NOTE: To get only the value use anAction.next().value otherwise the entire object will be printed. // ASYNC function example // Bunny needs to go grocery shopping for her friend’s birthday party. var groceries = ''; // Let’s create three functions that need to be called for Bunny. var buyCarrots = function () { groceries += 'carrots'; } var buyGrass = function () { groceries += ', grass'; } var buyApples = function () { groceries += ', and apples'; } // Bunny is in a hurry so you have to buy the groceries within certain amount of time! // This is an example of when you would use a timer with a Generator. // First store the functions within an array: var buyGroceries = [buyCarrots, buyGrass, buyApples]; // Then loop through the array within a Generator: // There are some issues doing this with the forEach, recreate this using a for loop. function* loopThrough(arr) { for(var i=0; i<arr.length; i++) { yield arr[i](); } } // add the array of three functions to the loopThrough function. var functions = loopThrough(buyGroceries); // Lastly, set the time you want paused before the next function call // using the setInterval method(calls a function/expression after a specific set time). var timedGroceryHunt = setInterval(function() { var functionCall = functions.next(); if(!functionCall.done) { console.log(`Bunny bought ${groceries}!`); }else { clearInterval(timedGroceryHunt); console.log(`Thank you! Bunny bought all the ${groceries} in time thanks to your help!`); } }, 1000); // Enter this code into your console to test it out! // after 1 second: => Bunny bought carrots! // after 1 second: => Bunny bought carrots, grass! // after 1 second: => Bunny bought carrots, grass, and apples! // after 1 second: => Thank you! Bunny bought all the carrots, grass, and apples in time thanks to your help!

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.