Skip to content

Instantly share code, notes, and snippets.

@jpina
Created November 25, 2015 11:03
Show Gist options
  • Save jpina/193c6f09e30b79fff47e to your computer and use it in GitHub Desktop.
Save jpina/193c6f09e30b79fff47e to your computer and use it in GitHub Desktop.
05 Queuing asynchronous actions
getJSON('story.json').then(function(story) {
return getJSON(story.chapterUrls[0]);
}).then(function(chapter1) {
console.log("Got chapter 1!", chapter1);
});
/*************************/
var storyPromise;
function getChapter(i) {
storyPromise = storyPromise || getJSON('story.json');
return storyPromise.then(function(story) {
return getJSON(story.chapterUrls[i]);
})
}
// and using it is simple:
getChapter(0).then(function(chapter) {
console.log(chapter);
return getChapter(1);
}).then(function(chapter) {
console.log(chapter);
});
/*
We don't download "story.json" until getChapter is called,
but the next time(s) getChapter is called we reuse the story
promise, so story.json is only fetched once.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment