Created
November 25, 2015 11:03
-
-
Save jpina/193c6f09e30b79fff47e to your computer and use it in GitHub Desktop.
05 Queuing asynchronous actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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