Skip to content

Instantly share code, notes, and snippets.

@SastraNababan
Created October 30, 2017 19:38
Show Gist options
  • Save SastraNababan/e3777b4f1d7f3f0c4f317d5643cb6cba to your computer and use it in GitHub Desktop.
Save SastraNababan/e3777b4f1d7f3f0c4f317d5643cb6cba to your computer and use it in GitHub Desktop.
Promise Chaining Example 1
const getPost = () => fetch('https://jsonplaceholder.typicode.com/posts/1')
const getAuthor = (id) => fetch('https://jsonplaceholder.typicode.com/users/' + id)
const getComment = (id) => fetch('https://jsonplaceholder.typicode.com/users/' + id)
getPost() // #1.fetch post
.then(postResponse => postResponse.json()) // #2. get & return post json
.then(postResponse => getAuthor(postResponse.id) // #3. fetch author
.then(authorResponse => authorResponse.json() // #4 get & return author json
.then(authorResponse => getComment(postResponse.id) // #5 fetch comment
.then(commentResponse => commentResponse.json()) // #6 get & return comment json
.then(commentResponse => { // #7 time to combine all results
return ({postResponse,authorResponse,commentResponse}) // #8 combine & return all reponses
})
)
)
.then(results => { // #9 read all responses
console.log(results.postResponse)
console.log(results.authorResponse)
console.log(results.commentResponse)
})
)
.catch(error => console.log(error)) //# 10 error handling
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment