8. next()
All an object needs to be an iterator is a next* method, which
returns an object with a value property and a done property.
* Iterators generally also include a throw method for throwing errors.
9. for … of
function *hoover() {
console.log('Preparing to yield "Boulder"');
yield 'Boulder';
console.log('All done yielding');
}
for (let x of hoover()) {
console.log(`x is ${x}`);
}
// Output:
/*
Preparing to yield "Boulder"
x is Boulder
All done yielding
*/
17. Prompt
We already know how to pause execution in the middle of
a function.
function getName() {
var name = prompt('What's your name?');
return name;
}
But now we can pause execution without freezing the entire
browser.
19. Avoid callback inception
$el.on('click', function(evt) {
$.ajax('/vsearch/pj', function(data) {
dust.render('tl/shared/person', data, function
(err, out) {
$el.html(out);
// Please, make it stop!
})
})
});
remember?
20. yield is the new callback
function *showFeed() {
let data = yield request('/feed');
let dom = yield feedTemplate.render(data);
document.querySelector('#feed-container').appendChild(dom);
}
// To use
runMyGenerator(showFeed);
21. Behind the Scenes - request
function request(url) {
if (cachedResponses[url]) {
return cachedResponses[url];
} else {
return Promise(function(resolve, reject) {
makeAjaxRequest(url, resolve);
});
}
}
22. Behind the Scenes - runMyGenerator
function runMyGenerator(gen) {
let iter = gen();
let yielded;
(function iterate(val) {
yielded = iter.next(val);
if (!yielded.done) {
if ('then' in yielded.value) {
// Wait for the promise to resolve before the next iteration
yielded.value.then(iterate);
} else {
// Next
setTimeout(function() {
iterate(val);
}, 0);
}
}
})();
}
23. Sneak Peak: ES7 Async Functions
async function showFeed(url) {
let data = await request('/feed');
let dom = await feedTemplate.render(data);
document.querySelector('#feed-container').appendChild(dom);
}
showFeed('/feed');