functionspawn(generatorFunc) { functioncontinuer(verb, arg) { var result; try { result = generator[verb](arg); } catch (err) { returnPromise.reject(err); } if (result.done) { return result.value; } else { returnPromise.resolve(result.value).then(callback, errback); } } var generator = generatorFunc(); var callback = continuer.bind(continuer, "next"); var errback = continuer.bind(continuer, "throw"); return callback(); }
spawn(function *() { "use strict"; try { // 'yield' effectively does an async wait, returning the result of the promise let story = yield getJson('story.json'); addHtmlToPage(story.heading); // Map our array of chapter urls // to an array of chapter json promises. // This makes sure they all download parallel. let chapterPromises = story.chapterUrls.map(getJson); // Can't use chapterPromises.forEach, because yielding within doesn't work for (let i = 0, chapterPromise; chapterPromise = chapterPromises[i]; i++) { // Wait for each chapter to be ready, then add it to the page let chapter = yield chapterPromise; addHtmlToPage(chapter.html); } addTextToPage("All done"); } catch (err) { // try/catch just works, rejected promises are thrown here addTextToPage("Argh, broken: " + err.message); } document.querySelector('.spinner').style.display = 'none'; });